Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to zero-padded binary string

Tags:

java

binary

when converting int to binary, how to output it to 8 character, currently it only display 1 and short of the 7 zeros

code

int x = 1;
String bin = Integer.toBinaryString(x);
System.Out.Println(bin);

example output to 0000 0001

like image 459
newbieprogrammer Avatar asked Dec 11 '22 07:12

newbieprogrammer


1 Answers

I am not sure if that is what you mean but how about something like

String.format("%8s", Integer.toBinaryString(1)).replace(' ', '0')

will generate 00000001

like image 99
Pshemo Avatar answered Dec 13 '22 19:12

Pshemo