简体   繁体   中英

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.

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? If yes, what format String should I use? Thanks in advance!

Edit: The data array is of dynamic length, so should the number of leading zeros.

For padding with, say, 5 leading zeroes, this will work:

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.

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.

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. Hope this is fine.

1] Building the format string

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

2] Integer to Binary Conversion

    String dataStr = Integer.toBinaryString(data);

3] Padding with Leading Zeros

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

The major difference here is the 3rd step. 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). 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. Long can be used, but, even that has limitations.
2] BigInteger can be used, but, I'm sure, it will be the costliest at runtime compared to all the other methods. So, it seems, unless only shorter binary strings are expected, replace() is the better method.

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

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