简体   繁体   中英

Convert integer to zero-padded binary string

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

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

您可以使用零填充二进制字符串。

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

转换,检查结果长度,如果<8则添加零。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM