Fill string with leading zeros

9

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();
} 
    
asked by anonymous 30.10.2014 / 11:34

3 answers

5

Dude did not test but this should work!

public String converteDecimalParaBinario(int valor) {
   int resto = -1;
   StringBuilder sb = new StringBuilder();
   int len=0;   

   if (valor == 0) {
      return "0000";
   }

   // 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);
   }
   len = sd.length();
   while(len<4){
       sd="0"+sd;
       len++;
   }
   return sb.toString();
} 

What I did:

I started a variable of type int called len and assigns the size of sd to len with the command len = sd.length(); . If len is less than 4 add 0 to the left, repeat until len is equal to 4. returns sd.

    
30.10.2014 / 11:49
13

You can use the DecimalFormat class to format its output value. So:

    //coloque isso no final do seu método converteDecimalParaBinario
    DecimalFormat df = new DecimalFormat("0000");
    return df.format(Integer.parseInt(sb.toString()));

You say in the statement that you have a qtd variable that indicates how many digits the output should have, so the build of your DecimalFormat object must be variable by that amount. To make this variable amount of digits, you can make a for and build your pattern. Example:

    int qtd = 5;
    StringBuilder pattern = new StringBuilder();
    for(int i=0; i<qtd; i++) {
        pattern.append("0");
    }
    DecimalFormat df = new DecimalFormat(pattern.toString());

If it is not part of your job to convert the number to binary, you can also use the toBinaryString() method of the Integer class to do the conversion for you. Example:

import java.text.DecimalFormat;
public class Bin {
    public static void main(String[] args) {
        System.out.println(converteDecimalParaBinario(4));
    }
    public static String converteDecimalParaBinario(int valor) {
        int qtd = 5;
        StringBuilder pattern = new StringBuilder();
        for(int i=0; i<qtd; i++) {
            pattern.append("0");
        }
        DecimalFormat df = new DecimalFormat(pattern.toString());
        return df.format(Integer.parseInt(Integer.toBinaryString(valor)));
    } 
}

Output:

  

00100

To change the amount of digits the output will have, simply change the value of the variable qtd .

    
30.10.2014 / 11:51
8

You can do this if it is string :

String str = "123";
String formatted = ("0000" + str).substring(str.length());

Note: Enter a zero for each digit you want, ie 4 digits that you mention in the question need 4 zeros.

Or if it is a number:

Int number = 123;
String formatted = String.format("%04d", number);

Note: $ 04d is for table digits, $ 05d is for 5 digits, etc. ...

Anyway, the second option is always better: have the variable with the correct type and format the desired way the number using the format .

For your particular case, you could do the following at the time of returning the value:

String formatado = String.format("%04d", Integer.parseInt(sb.toString()));
return formatado;

Example

/* package superBuBu; */

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {

        int valor = 1;
        int resto = -1;

        StringBuilder sb = new StringBuilder();

        if (valor == 0) {
            System.out.println("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);
        }

        String formatado = String.format("%04d", Integer.parseInt(sb.toString()));

        System.out.println(formatado);
    }
}

Example working on Ideone .

    
30.10.2014 / 11:42