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.
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.