How to get 0-padded binary representation of an in

2018-12-31 12:18发布

for example, for 1, 2, 128, 256 the output can be (16 digits):

0000000000000001
0000000000000010
0000000010000000
0000000100000000

I tried

String.format("%16s", Integer.toBinaryString(1));

it puts spaces for left-padding:

`               1'

How to put 0s for padding. I couldn't find it in Formatter. Is there another way to do it?

Thanks in advance.

P.S. this post describes how to format integers with left 0-padding, but it is not for the binary representation.

15条回答
明月照影归
2楼-- · 2018-12-31 12:22

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

private String toBinaryString32(int i) {
    String binaryWithOutLeading0 = Integer.toBinaryString(i);
    return "00000000000000000000000000000000"
            .substring(binaryWithOutLeading0.length())
            + binaryWithOutLeading0;
}
查看更多
心情的温度
3楼-- · 2018-12-31 12:28

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)

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....

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;
查看更多
谁念西风独自凉
4楼-- · 2018-12-31 12:30

I would write my own util class with the method like below

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;

查看更多
情到深处是孤独
5楼-- · 2018-12-31 12:31

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:

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 this so. 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:

String.format("%016d", new BigInteger(Integer.toBinaryString(1)))
查看更多
栀子花@的思念
6楼-- · 2018-12-31 12:32

A naive solution that work would be

String temp = Integer.toBinaryString(5);
while (temp.length() < Integer.SIZE) temp = "0"+temp; //pad leading zeros
temp = temp.substring(Integer.SIZE - Short.SIZE); //remove excess

One other method would be

String temp = Integer.toBinaryString((m | 0x80000000));
temp = temp.substring(Integer.SIZE - Short.SIZE);

This will produce a 16 bit string of the integer 5

查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 12:36

try...

String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));

I dont think this is the "correct" way to doing this... but it works :)

查看更多
登录 后发表回答