将整数转换为零填充的二进制字符串

2022-01-09 00:00:00 binary java

int转二进制时,如何输出为8个字符,目前只显示1,少了7个零

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

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

示例输出到 0000 0001

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')

会生成00000001

相关文章