Find out number of bits needed to represent a positive integer in binary?

后端 未结 14 1743
醉酒成梦
醉酒成梦 2020-12-05 09:35

This is probably pretty basic, but to save me an hour or so of grief can anyone tell me how you can work out the number of bits required to represent a given positive intege

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 10:35

    My Java is a bit rusty, but the language-agnostic answer (if there is a "log2" function and a "floor" function available) would be:

    numberOfBits = floor(log2(decimalNumber))+1
    

    Assuming that "decimalNumber" is greater than 0. If it is 0, you just need 1 bit.

提交回复
热议问题