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

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

    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

提交回复
热议问题