How to determine how many bytes an integer needs?

前端 未结 22 1566
悲&欢浪女
悲&欢浪女 2020-12-13 02:13

I\'m looking for the most efficient way to calculate the minimum number of bytes needed to store an integer without losing precision.

e.g.

int: 10 = 1 byte
         


        
22条回答
  •  隐瞒了意图╮
    2020-12-13 03:08

    The function to find the position of the first '1' bit from the most significant side (clz or bsr) is usually a simple CPU instruction (no need to mess with log2), so you could divide that by 8 to get the number of bytes needed. In gcc, there's __builtin_clz for this task:

    #include 
    int bytes_needed(unsigned long long x) {
       int bits_needed = sizeof(x)*CHAR_BIT - __builtin_clzll(x);
       if (bits_needed == 0)
          return 1;
       else
          return (bits_needed + 7) / 8;
    }
    

    (On MSVC you would use the _BitScanReverse intrinsic.)

提交回复
热议问题