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

前端 未结 6 1249
暗喜
暗喜 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:41

    Do a binary search instead of a linear search.

    if ((n >> 16) != 0)
    {
        r += 16;
        n >>= 16;
    }
    
    if ((n >> 8) != 0)
    {
        r += 8;
        n >>= 8;        
    }
    
    if ((n >> 4) != 0)
    {
        r += 4;
        n >>= 4;        
    }
    
    // etc.
    

    If your hardware has bit-scan-reverse, an even faster approach would be to write your routine in assembly language. To keep your code portable, you could do

    #ifdef ARCHITECTURE_WITH_BSR
       asm // ...
    #else
       // Use the approach shown above
    #endif
    

提交回复
热议问题