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

前端 未结 17 2317
我在风中等你
我在风中等你 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:43

    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;
    }
    

提交回复
热议问题