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

前端 未结 6 1260
暗喜
暗喜 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

    You would have to check the execution time to figure the granularity, but my guess is that doing 4 bits at a time, and then reverting to one bit at a time would make it faster. Log operations would probably be slower than logical/bit operations.

    if (n < 0) return 32;
    int r = 0;
    while (n && 0x7FFFFFF0) {
      r+=4;
      n >>= 4; }
    while (n) {
      r++;
      n >>= 1; }
    return r;
    

提交回复
热议问题