Ajax
Ajax

Reputation: 150

How to get Leading zeros for binary numbers in java

I'm trying to convert octal numbers to binary numbers using this code

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter octal number: ");
String oct = br.readLine();
int i= Integer.parseInt(oct,8);
String binary=Integer.toBinaryString(i);
System.out.println("Octal Number: "+binary);

but the issue here how to get the leading zeros

Upvotes: 0

Views: 260

Answers (2)

WJS
WJS

Reputation: 40044

Try this.

      int[] vals = { 10, 34, 99, 1002, 40
      };
      for (int v : vals) {
         // the 07 means a field width of 7 with 0's padding on left.
         // th o means octal and the %n is newline.
         System.out.printf("%07o%n", v);
      }

      //This does the same thing but returns a formatted string.
      String paddedVal = String.format("%07o", 48);
      System.out.println(paddedVal);

For String already in octal.

      String octalVal = "57";
      paddedVal = String.format("%07o", Integer.valueOf(octalVal, 8));
      System.out.println(paddedVal);
      // should print 0000057

For binary numbers.


      octalVal = "57";
      String bin = Integer.toBinaryString(Integer.valueOf(octalVal));
      String paddedBin =
            "00000000000000000000000000000".substring(0, 32 - bin.length())
                  + bin;
      System.out.println(paddedBin);

Upvotes: 3

Antoniossss
Antoniossss

Reputation: 32517

Its kind of simple task. Lets try to complement to multiply of 8;

public static void main(String[] args) {
    System.out.println(binaryPadLeft(Integer.toBinaryString(127)));
}

private static String binaryPadLeft(String number) {
    StringBuilder b = new StringBuilder();
    int mod = number.length() % 8;
    if (mod > 0)
        for (int i = 0, p = 8 - mod; i < p; i++) {
            b.append('0');
        }
    b.append(number);
    return b.toString();
}

gives 01111111

for 120 it yelds 01010000

Upvotes: 1

Related Questions