Convert base 10 to base 2

Asked

Viewed 552 times

1

I’m trying to create an algorithm that converts base 10 to base 2. It is apparently converting, but is 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 to return the right value? I would like a solution only using logic. I know that java has a method to do this.

Besides, how can I invert these values without using vector?

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

  • Good afternoon. The way I did it is wrong? Because in my studies I have not studied method. I’m trying to do it purely with the basics of programming logic. Why use Stringbuffer? And binary.append?

  • There enters the question that you have not reversed the writing form as it is done in that line System.out.println(binario.reverse().toString()). As with the reverce() the number will be in the correct order

  • That StringBuffer binario = new StringBuffer() you can trade for this String binario = " " and then on that line binario.append(b) trade for this binario = binario + b this way you will be concatenating the value of binario plus the value of b

Browser other questions tagged

You are not signed in. Login or sign up in order to post.