How to get 0-padded binary representation of an integer in java?

前端 未结 17 2251
我在风中等你
我在风中等你 2020-11-22 08:23

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

0000000000000001
0000000000000010
0000000010000000
0000000100000000
17条回答
  •  旧巷少年郎
    2020-11-22 08:34

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

提交回复
热议问题