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

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

    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;
    

提交回复
热议问题