How to determine how many bytes an integer needs?

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

    I know this question didn't ask for this type of answer but for those looking for a solution using the smallest number of characters, this does the assignment to a length variable in 17 characters, or 25 including the declaration of the length variable.

    //Assuming v is the value that is being counted...
    int l=0;
    for(;v>>l*8;l++);
    

提交回复
热议问题