How to determine how many bytes an integer needs?

前端 未结 22 1567
悲&欢浪女
悲&欢浪女 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:06

    Assuming a byte is 8 bits, to represent an integer x you need [log2(x) / 8] + 1 bytes where [x] = floor(x).

    Ok, I see now that the byte sizes aren't necessarily a power of two. Consider the byte sizes b. The formula is still [log2(x) / b] + 1.

    Now, to calculate the log, either use lookup tables (best way speed-wise) or use binary search, which is also very fast for integers.

提交回复
热议问题