10
I’m doing a work of Operating Systems and need to turn decimal numbers into binaries. So far so good, because the method below takes an integer and converts to binary. My problem is the following:
When I put, for example (integer 1), it returns me correctly 1. But I have a stored value that would be the number of digits, for example (Qtd = 4). I would like the string to appear this way: 0001 with four digits.
It would be possible in this method to perform this procedure, regardless of the value of the variable number of digits?
public String converteDecimalParaBinario(int valor) {
int resto = -1;
StringBuilder sb = new StringBuilder();
if (valor == 0) {
return "0";
}
// enquanto o resultado da divisão por 2 for maior que 0 adiciona o resto ao início da String de retorno
while (valor > 0) {
resto = valor % 2;
valor = valor / 2;
sb.insert(0, resto);
}
return sb.toString();
}
+1 for making the API work for you instead of reinventing the wheel.
– Piovezan
Thanks for the answers, but I already got it with the @Joannis proposal
– Rodrigo Segatto
@Rodrigosegatto, here at Stack we thank with positive votes ;)
– brasofilo