What is the fastest way to calculate the number of bits needed to store a number

前端 未结 6 1253
暗喜
暗喜 2021-01-12 02:50

I\'m trying to optimize some bit packing and unpacking routines. In order to do the packing I need to calculate the number of bits needed to store integer values. Here is th

6条回答
  •  情书的邮戳
    2021-01-12 03:31

    Non-portably, use the bit-scan-reverse opcode available on most modern architectures. It's exposed as an intrinsic in Visual C++.

    Portably, the code in the question doesn't need the edge-case handling. Why do you require one bit for storing 0? In any case, I'll ignore the edges of the problem. The guts can be done efficiently thus:

    if (n >> 16) { r += 16; n >>= 16; }
    if (n >>  8) { r +=  8; n >>=  8; }
    if (n >>  4) { r +=  4; n >>=  4; }
    if (n >>  2) { r +=  2; n >>=  2; }
    if (n - 1) ++r;
    

提交回复
热议问题