0

When using the Integer.toBinaryString() method to convert decimal to binary my program keeps returning the binary code without the leading 0's in the binary representation. How can I make sure that the zeros aren't lost? For example if the code is:

String binary = Integer.toBinaryString(84);

I get 1010100 instead of 01010100

How can I make sure that the leading zero doesn't disappear ?

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • `String binary = Integer.toBinaryString(84)` convert decimal to binary not ascci to binary. – Masudul Dec 12 '13 at 13:32
  • @Masud - Actually, it converts binary to character. – Hot Licks Dec 12 '13 at 13:33
  • possible duplicate of [How to get 0-padded binary representation of an integer in java?](http://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java) – devnull Dec 12 '13 at 13:36

1 Answers1

3

You can format the result from the Integer.toBinaryString(int i) method with the String.format(String pattern, Object ... args) method:

String binaryString = Integer.toBinaryString(84);
String format = String.format("%8s", binaryString).replace(' ', '0');
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147