Convert base 10 to base 2

1

I'm trying to create an algorithm that converts base 10 to base 2. It's apparently converting, but it's not returning the right binary value.

package basicojava;
import java.util.Scanner;
public class Ex13 {
    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        int num;
        int resto;


        System.out.println("Digite um numero em decimal: ");
        num = sc.nextInt();

        do {
            resto = num % 2;
            num = num / 2;
            System.out.println(resto);
        } while (num != 0);

    }
}

What do I need to do to get it right? I would like a solution only using logic. I know java has a method to do this.

What's more, how can I reverse these values without using a vector?

    
asked by anonymous 15.08.2017 / 21:51

1 answer

2
public void binario(int numero) {
        int d = numero;
        StringBuffer binario = new StringBuffer(); // guarda os dados
        while (d > 0) {
            int b = d % 2;
            binario.append(b);
            d = d >> 1; // é a divisão que você deseja
        }
        System.out.println(binario.reverse().toString()); // inverte a ordem e imprime
    }

Help video

    
15.08.2017 / 21:57