How to determine how many bytes an integer needs?

前端 未结 22 1558
悲&欢浪女
悲&欢浪女 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条回答
  •  萌比男神i
    2020-12-13 02:57

    You need exactly the log function

    nb_bytes = floor(log(x)/log(256))+1 if you use log2, log2(256) == 8 so

    floor(log2(x)/8)+1

提交回复
热议问题