I'm doing an OS work and need to turn decimal numbers into binaries. So that's fine, because the method below takes an integer and converts to binary. My problem is this:
When I put it, 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 look like this: 0001 with four digits.
How would you 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();
}