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

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

    I would like to add some other alternatives, just for the sake of completeness:

    1 BigInteger.valueOf(i).bitLength()

    Not very fast. Furthermore, BigInteger.bitLength() it's bugged and unreliable (fixed in Java7), since when more than Integer.MAX_VALUE bits are needed (freakishly high input number needed!! [such as 1 left-shifted Integer.MAX_VALUE times, aka 2^Integer.MAX_VALUE]) the result overflows and negative numbers appear for the next 2^(2*Integer.MAX_VALUE)-2^Integer.MAX_VALUE numbers, which is a number so high your head could explode. Note that it is estimated the universe containes some 10^80 atoms; that number is 2^4G (G as in Giga, 1024*1024*1024).

    2

    static int neededBits(int i)
    {
        assert i > 0;
        int res;
        int sh;
        res = ((i > 0xFFFF) ? 1 : 0) << 4;
        i >>= res;
        sh = ((i > 0xFF) ? 1 : 0) << 3;
        i >>= sh;
        res |= sh;
        sh = ((i > 0xF) ? 1 : 0) << 2;
        i >>= sh;
        res |= sh;
        sh = ((i > 0x3) ? 1 : 0) << 1;
        i >>= sh;
        res |= sh;
        res |= (i >> 1);
        return res + 1;
    }
    

    A very fast solution, but still half as fast as ye olde 32 - Integer.numberOfLeadingZeros(i);.

提交回复
热议问题