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

后端 未结 8 1193
有刺的猬
有刺的猬 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条回答
  •  长发绾君心
    2020-12-30 13:40

    This is a common homework problem. There's a cool loop that you can write that will compute the smallest power of 2 >= your target number n.

    Since it's a power of 2, the base 2 logarithm is the number of bits. But the Java math library only offers natural logarithm.

    math.log( n ) / math.log(2.0) 
    

    is the number of bits.

提交回复
热议问题