Convert integer to zero-padded binary string

后端 未结 3 1148
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 08:42

when converting int to binary, how to output it to 8 character, currently it only display 1 and short of the 7 zeros

code

int x = 1;
String bin = Int         


        
相关标签:
3条回答
  • 2020-12-10 09:26

    You can pad your binary string with zeroes.

    String bin = String.format("%8s", Integer.toBinaryString(x).replace(' ', '0');
    
    0 讨论(0)
  • 2020-12-10 09:27

    I am not sure if that is what you mean but how about something like

    String.format("%8s", Integer.toBinaryString(1)).replace(' ', '0')
    

    will generate 00000001

    0 讨论(0)
  • 2020-12-10 09:36

    Convert, check the resulting length and add zeros if < 8.

    0 讨论(0)
提交回复
热议问题