How to determine how many bytes an integer needs?

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

    You need to raise 256 to successive powers until the result is larger than your value.

    For example: (Tested in C#)

    long long limit = 1;
    int byteCount;
    
    for (byteCount = 1; byteCount < 8; byteCount++) {
        limit *= 256;
        if (limit > value)
            break;
    }
    

    If you only want byte sizes to be powers of two (If you don't want 65,537 to return 3), replace byteCount++ with byteCount *= 2.

提交回复
热议问题