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

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

    You can also do it like this, if you don't want to modify the original value.

    unsigned int value = 11;
    unsigned int count = 0;
    if(value > 0)
    {
        for(int i=1;i shift one to left
        {
            ++count;
        }
    }
    

    Note: Let the compiler worry about turning i*=2 into a bit shift operation to improve performance.

    For the visual thinkers among us:

    64 32 16  8  4  2  1
     0  0  0  1  0  1  1  -> binary representation of decimal number 'value' = 11 (=1+2+8)
    

    We start with i=1 at the right. Then we keep multiplying by two, for as long as i < value. In the meanwhile, we keep track of how many bits we went to the left.

    So in this example, as soon as i reaches 16 the value is larger than 11, and thus we stop. And we will then have counted 4 bits: 1 *2 *2 *2 *2 = 16 (=2^4).

    Careful with signed numbers. When dealing with signed numbers that may be positive or negative, you would first have to multiply the negative numbers by -1. Additionally, you would have to consider how you want to take the sign-bit into account.

提交回复
热议问题