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

后端 未结 14 1613
醉酒成梦
醉酒成梦 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:39

    Taking the two based log of the number will report the number of bits required to store it.

    0 讨论(0)
  • 2020-12-05 10:41

    Binary search over the the exponents of 2 is faster than the bit shift (top voted answer) solution, which might be valuable if the numbers are huge (thousands of decimal digits), you know the maximum available bits and you do not want to generate the tables:

        int  minExpVal   = 0;
        int  maxExpVal   = 62;
        int  medExpVal   = maxExpVal >> 1;
        long medianValue = 0l;
    
        while (maxExpVal - minExpVal > 1) {
            medianValue = 1l << medExpVal;
            if (value > medianValue) {
                minExpVal = medExpVal;
            } else {
                maxExpVal = medExpVal;
            }
            medExpVal = (minExpVal + maxExpVal) >> 1;
        }
    
        return value == 1l << maxExpVal ?  maxExpVal  + 1 : maxExpVal;
    

    However, the solution using the leading zeros would be still by far faster:

    return Long.SIZE - Long.numberOfLeadingZeros(value);
    

    Benchmarks:

    Leading zeros time is: 2 ms
    BinarySearch time is: 95 ms
    BitShift time is: 135 ms
    
    0 讨论(0)
提交回复
热议问题