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

后端 未结 14 1715
醉酒成梦
醉酒成梦 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条回答
  •  再見小時候
    2020-12-05 10:30

    For non-negative values, probably the most direct answer is:

    java.math.BigDecimal.valueOf(value).bitLength()
    

    (For negative numbers it will give the bit length of one less than the absolute value, rather than infinity you'd expect from two's complement notation.)

提交回复
热议问题