• February 6th, 2012, 07:45 PM
Deprogrammer
How do I convert a hexadecimal number to binary keeping the leading zeros? For the conversion itself I am using:
String stringName = Integer.toBinaryString(int in 0x format);, however, this truncates the leading zeros rendering the conversion borderline useless. Using String formattedString = String.format("%032d", int in 0x format); works only on an int not on a string. I am sure there must be an obvious solution that I am overlooking as I would hate to write relatively complicated code for such a mundane procedure.

• February 6th, 2012, 08:27 PM
pbrockway2
Quote:

How do I convert a hexadecimal number to binary keeping the leading zeros? ... Using String formattedString = String.format("%032d", int in 0x format); works only on an int not on a string.
When I try that I get a decimal string with width 32, not a binary one.

Code :

```public class Test { public static void main(String[] args) { String formattedString = String.format("%032d", 0xCAFE); // prints 00000000000000000000000000051966 System.out.println(formattedString); } }```

The Formatter API docs reveal that there are octal, decimal and hex numeric formats offered (with zero as a padding character), but no binary (or other base). So it looks like toBinaryString() is the way to go.

toBinaryString() returns a string and, alas, you get spaces inserted when the string is right aligned to a specified width, not zero (or any other character.)

It looks like the most straight forward approach - using standard library formatting methods - is to use toBinaryString(), or one of the numerous toString() methods, format this to have the width you want with %32s for example, then replace the spaces with zeros.