如何在java中获得整数的0填充二进制表示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4421400/
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
How to get 0-padded binary representation of an integer in java?
提问by khachik
for example, for 1, 2, 128, 256
the output can be (16 digits):
例如,对于1, 2, 128, 256
输出可以是(16 位):
0000000000000001
0000000000000010
0000000010000000
0000000100000000
I tried
我试过
String.format("%16s", Integer.toBinaryString(1));
it puts spaces for left-padding:
它为左填充放置了空间:
` 1'
How to put 0
s for padding. I couldn't find it in Formatter. Is there another way to do it?
如何将0
s 用于填充。我在Formatter 中找不到它。还有另一种方法吗?
P.S. this postdescribes how to format integers with left 0-padding, but it is not for the binary representation.
PS这篇文章描述了如何用左 0 填充来格式化整数,但它不是用于二进制表示。
采纳答案by Samuel Parsonage
I think this is a suboptimal solution, but you could do
我认为这是一个次优的解决方案,但你可以这样做
String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')
回答by Paul
try...
尝试...
String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));
I dont think this is the "correct" way to doing this... but it works :)
我不认为这是这样做的“正确”方式......但它有效:)
回答by Zoran Regvart
There is no binary conversion built into the java.util.Formatter, I would advise you to either use String.replace to replace space character with zeros, as in:
java.util.Formatter 中没有内置二进制转换,我建议您使用 String.replace 用零替换空格字符,如下所示:
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")
Or implement your own logic to convert integers to binary representation with added left padding somewhere along the lines given in thisso. Or if you really need to pass numbers to format, you can convert your binary representation to BigInteger and then format that with leading zeros, but this is very costly at runtime, as in:
或者实现你自己的逻辑来将整数与沿指定的行加左填充的地方二进制表示该如此。或者,如果您确实需要将数字传递给格式,则可以将二进制表示形式转换为 BigInteger,然后使用前导零对其进行格式化,但这在运行时非常昂贵,例如:
String.format("%016d", new BigInteger(Integer.toBinaryString(1)))
回答by AlexR
I do not know "right" solution but I can suggest you a fast patch.
我不知道“正确”的解决方案,但我可以建议你一个快速补丁。
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");
I have just tried it and saw that it works fine.
我刚刚尝试过,发现它工作正常。
回答by Tom Spencer
I was trying all sorts of method calls that I haven't really used before to make this work, they worked with moderate success, until I thought of something that is so simple it just might work, and it did!
我尝试了各种我以前从未真正使用过的方法调用来完成这项工作,它们取得了一定的成功,直到我想到了一些非常简单的东西,它可能会起作用,并且确实如此!
I'm sure it's been thought of before, not sure if it's any good for long string of binary codes but it works fine for 16Bit strings. Hope it helps!! (Note second piece of code is improved)
我确定之前已经考虑过它,不确定它对长串二进制代码是否有好处,但它适用于 16Bit 字符串。希望能帮助到你!!(注意第二段代码已改进)
String binString = Integer.toBinaryString(256);
while (binString.length() < 16) { //pad with 16 0's
binString = "0" + binString;
}
Thanks to Will on helping improve this answer to make it work with out a loop. This maybe a little clumsy but it works, please improve and comment back if you can....
感谢 Will 帮助改进这个答案,使其在没有循环的情况下工作。这可能有点笨拙,但它有效,如果可以,请改进并评论......
binString = Integer.toBinaryString(256);
int length = 16 - binString.length();
char[] padArray = new char[length];
Arrays.fill(padArray, '0');
String padString = new String(padArray);
binString = padString + binString;
回答by Bunarro
You can use Apache Commons StringUtils. It offers methods for padding strings:
您可以使用 Apache Commons StringUtils。它提供了填充字符串的方法:
StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');
回答by user3608934
This is an old trick, create a string with 16 0's then append the trimmed binary string you got from String.format("%s", Integer.toBinaryString(1)) and use the right-most 16 characters, lopping off any leading 0's. Better yet, make a function that lets you specify how long of a binary string you want. Of course there are probably a bazillion other ways to accomplish this including libraries, but I'm adding this post to help out a friend :)
这是一个老技巧,创建一个包含 16 个 0 的字符串,然后附加从 String.format("%s", Integer.toBinaryString(1)) 获得的修剪后的二进制字符串,并使用最右边的 16 个字符,去掉任何前导0 的。更好的是,创建一个函数,让您指定所需的二进制字符串的长度。当然,可能有无数其他方法可以实现这一点,包括图书馆,但我添加这篇文章是为了帮助朋友:)
public class BinaryPrinter {
public static void main(String[] args) {
System.out.format("%d in binary is %s\n", 1, binaryString(1, 4));
System.out.format("%d in binary is %s\n", 128, binaryString(128, 8));
System.out.format("%d in binary is %s\n", 256, binaryString(256, 16));
}
public static String binaryString( final int number, final int binaryDigits ) {
final String pattern = String.format( "%%0%dd", binaryDigits );
final String padding = String.format( pattern, 0 );
final String response = String.format( "%s%s", padding, Integer.toBinaryString(number) );
System.out.format( "\npattern = '%s'\npadding = '%s'\nresponse = '%s'\n\n", pattern, padding, response );
return response.substring( response.length() - binaryDigits );
}
}
回答by bento
A simpler version of user3608934's idea "This is an old trick, create a string with 16 0's then append the trimmed binary string you got ":
user3608934 想法的更简单版本“这是一个老技巧,创建一个包含 16 个 0 的字符串,然后附加您得到的修剪后的二进制字符串”:
private String toBinaryString32(int i) {
String binaryWithOutLeading0 = Integer.toBinaryString(i);
return "00000000000000000000000000000000"
.substring(binaryWithOutLeading0.length())
+ binaryWithOutLeading0;
}
回答by Cr4paud
Here a new answer for an old post.
这是旧帖子的新答案。
To pad a binary value with leading zeros to a specific length, try this:
要将带有前导零的二进制值填充到特定长度,请尝试以下操作:
Integer.toBinaryString( (1 << len) | val ).substring( 1 )
If len = 4
and val = 1
,
如果len = 4
, val = 1
,
Integer.toBinaryString( (1 << len) | val )
returns the string "10001"
, then
返回字符串"10001"
,然后
"10001".substring( 1 )
discards the very first character. So we obtain what we want:
丢弃第一个字符。所以我们得到了我们想要的:
"0001"
If val
is likely to be negative, rather try:
如果val
可能是负数,请尝试:
Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )
回答by Arseny Kovalchuk
I would write my own util class with the method like below
我会用下面的方法编写我自己的 util 类
public class NumberFormatUtils {
public static String longToBinString(long val) {
char[] buffer = new char[64];
Arrays.fill(buffer, '0');
for (int i = 0; i < 64; ++i) {
long mask = 1L << i;
if ((val & mask) == mask) {
buffer[63 - i] = '1';
}
}
return new String(buffer);
}
public static void main(String... args) {
long value = 0b0000000000000000000000000000000000000000000000000000000000000101L;
System.out.println(value);
System.out.println(Long.toBinaryString(value));
System.out.println(NumberFormatUtils.longToBinString(value));
}
}
}
Output:
输出:
5 101 0000000000000000000000000000000000000000000000000000000000000101
The same approach could be applied to any integral types. Pay attention to the type of mask
相同的方法可以应用于任何整数类型。注意口罩的类型
long mask = 1L << i;
long mask = 1L << i;