How to determine how many bytes an integer needs?

前端 未结 22 1532
悲&欢浪女
悲&欢浪女 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 02:49

    There are already a lot of answers here, but if you know the number ahead of time, in c++ you can use a template to make use of the preprocessor.

    template 
    struct RequiredBytes {
        enum : int { value = 1 + (N > 255 ? RequiredBits<(N >> 8)>::value : 0) };
    };
    
    template <>
    struct RequiredBytes<0> {
        enum : int { value = 1 };
    };
    
    const int REQUIRED_BYTES_18446744073709551615 = RequiredBytes<18446744073709551615>::value; // 8
    

    or for a bits version:

    template 
    struct RequiredBits {
        enum : int { value = 1 + RequiredBits<(N >> 1)>::value };
    };
    
    template <>
    struct RequiredBits<1> {
        enum : int { value = 1 };
    };
    
    template <>
    struct RequiredBits<0> {
        enum : int { value = 1 };
    };
    
    const int REQUIRED_BITS_42 = RequiredBits<42>::value; // 6
    

提交回复
热议问题