Convert integer to null binary string

when converting int to binary, how to output it to 8 characters, currently it only displays 1 and less than 7 zeros

code

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

Output example on 0000 0001

+4
source share
3 answers

I'm not sure if this is what you mean, but what about something like

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

will generate 00000001

+12
source

You can fill your binary string with zeros.

String bin = String.format("%8s", Integer.toBinaryString(x).replace(' ', '0');
+1
source

, , < 8.

0

Source: https://habr.com/ru/post/1527532/


All Articles