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

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

    Well, you can just count how many times you shift right before you're left with just zero:

    int value = 11;
    int count = 0;
    while (value > 0) {
        count++;
        value = value >> 1;
    }
    

提交回复
热议问题