(Java) Specify number of bits (length) when converting binary number to string?

后端 未结 8 1195
有刺的猬
有刺的猬 2020-12-30 13:03

I\'m trying to store a number as a binary string in an array but I need to specify how many bits to store it as.

For example, if I need to store 0 with two bits I ne

8条回答
  •  -上瘾入骨i
    2020-12-30 13:54

    Try this:

    String binaryString = String.format("%"+Integer.toString(size)+"s",Integer.toBinaryString(19)).replace(" ","0");
    

    where size can be any number the user wants

提交回复
热议问题