Java 将整数转换为零填充的二进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21856626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert integer to zero-padded binary string
提问by newbieprogrammer
when converting int to binary, how to output it to 8 character, currently it only display 1 and short of the 7 zeros
将int转换为二进制时,如何将其输出为8个字符,目前只显示1和7个零
code
代码
int x = 1;
String bin = Integer.toBinaryString(x);
System.Out.Println(bin);
example output to 0000 0001
示例输出到 0000 0001
采纳答案by Pshemo
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
会产生 00000001
回答by ohlmar
You can pad your binary string with zeroes.
您可以用零填充二进制字符串。
String bin = String.format("%8s", Integer.toBinaryString(x).replace(' ', '0');
回答by Smutje
Convert, check the resulting length and add zeros if < 8.
转换,检查结果长度并在 < 8 时添加零。