简体   繁体   English

使用Java中的前导零填充二进制字符串等于零(“0”)

[英]Pad a binary String equal to zero (“0”) with leading zeros in Java

Integer.toBinaryString(data)

gives me a binary String representation of my array data. 给我一个我的数组数据的二进制字符串表示。

However I would like a simple way to add leading zeros to it, since a byte array equal to zero gives me a "0" String. 但是我想要一个简单的方法来向它添加前导零,因为一个等于零的字节数组给了我一个“0”字符串。

I'd like a one-liner like this: 我想要像这样的单线:

String dataStr = Integer.toBinaryString(data).equals("0") ? String.format(format, Integer.toBinaryString(data)) : Integer.toBinaryString(data);

Is String.format() the correct approach? String.format()是正确的方法吗? If yes, what format String should I use? 如果是,我应该使用什么format String? Thanks in advance! 提前致谢!

Edit: The data array is of dynamic length, so should the number of leading zeros. 编辑: data数组具有动态长度,因此前导零的数量也应如此。

For padding with, say, 5 leading zeroes, this will work: 对于带有5个前导零的填充,这将起作用:

String.format("%5s", Integer.toBinaryString(data)).replace(' ', '0');

You didn't specify the expected length of the string, in the sample code above I used 5, replace it with the proper value. 你没有指定字符串的预期长度,在我用过的示例代码5中,用适当的值替换它。

EDIT 编辑

I just noticed the comments. 我刚注意到这些评论。 Sure you can build the pattern dynamically, but at some point you have to know the maximum expected size, depending on your problem, you'll know how to determine the value: 当然你可以动态地构建模式,但在某些时候你必须知道最大的预期大小,这取决于你的问题,你将知道如何确定值:

String formatPattern = "%" + maximumExpectedSize + "s";

This is what you asked for—padding is added only when the value is zero. 这就是你要求的填充在值为零时添加。

String s = (data == 0) ? String.format("%0" + len + 'd', 0) : Integer.toBinaryString(data);

If what you really want is for all binary values to be padded so that they are the same length, I use something like this: 如果您真正想要的是填充所有二进制值以使它们具有相同的长度,我使用如下所示:

String pad = String.format("%0" + len + 'd', 0);
String s = Integer.toBinaryString(data);
s = pad.substring(s.length()) + s;

Using String.format() directly would be the best, but it only supports decimal, hexadecimal, and octal, not binary. 直接使用String.format()将是最好的,但它只支持十进制,十六进制和八进制,而不是二进制。

You could override that function in your own class: 您可以在自己的类中覆盖该函数:

    public static String toBinaryString(int x){

        byte[] b = new byte[32]; // 32 bits per int
        int pos = 0;        
        do{
            x = x >> 1; // /2
            b[31-pos++] = (byte)(x % 2);
        }while(x > 0);

        return Arrays.toString(b);  
    }

This, in concept, is almost same as @Óscar López answer, but different methods are used, so i thought i should post it. 在概念上,这与@ÓscarLópez答案几乎相同,但使用了不同的方法,所以我认为我应该发布它。 Hope this is fine. 希望这很好。

1] Building the format string 1]构建格式字符串

    String format = "%0" + totalDigits + "d";

2] Integer to Binary Conversion 2]整数到二进制转换

    String dataStr = Integer.toBinaryString(data);

3] Padding with Leading Zeros 3]用前导零填充

    dataStr = String.format(format, new Integer(dataStr));

The major difference here is the 3rd step. 这里的主要区别是第3步。 I believe, its actually a hack. 我相信,它实际上是一个黑客。 @erickson is right in String.format() not supporting binary, hence, i converted the binary number to an integer (not its equivalent), ie, "100" will be converted to hundred (100), not four(4). @erickson在String.format()不支持二进制文件,因此,我将二进制数转换为整数(不等价),即“100”将转换为百(100),而不是四(4)。 I then used normal formatting. 然后我使用普通格式。

Not sure about how much optimized this code is, but, i think its more easy to read, but, maybe, its just me. 不知道这个代码有多少优化,但是,我认为它更容易阅读,但是,也许,它只是我。

EDIT 编辑
1] Buffer Over-run is possible for longer binary strings. 1]缓冲区溢出可用于更长的二进制字符串。 Long can be used, but, even that has limitations. 可以使用很Long ,但是,即使这有限制。
2] BigInteger can be used, but, I'm sure, it will be the costliest at runtime compared to all the other methods. 2]可以使用BigInteger ,但是,我敢肯定,与其他所有方法相比,它在运行时成本最高。 So, it seems, unless only shorter binary strings are expected, replace() is the better method. 因此,似乎除非只需要更短的二进制字符串,否则replace()是更好的方法。

Seniors, 老年人,
please correct me if I'm wrong. 如果我错了,请纠正我。
Thanks. 谢谢。

would this satisfy your needs? 这会满足你的需求吗?

String dataStr = data == 0 ? "00" +   Integer.toBinaryString(data)  : Integer.toBinaryString(data);

edit: noticed the comment about dynamic length: probably some of the other answers are more suited:) 编辑:注意到关于动态长度的评论:可能其他一些答案更适合:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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