我正在寻找最有效的方法来计算存储整数所需的最小字节数,同时不会失去精度。
e.g.
int: 10 = 1 byte
int: 257 = 2 bytes;
int: 18446744073709551615 (UINT64_MAX) = 8 bytes;
谢谢
顺便说一句,这是为了一个会被调用成百万次的哈希函数
字节大小也不必是2的幂次方
最快的解决方案似乎是基于tronics的答案:
int bytes;
if (hash <= UINT32_MAX)
{
if (hash < 16777216U)
{
if (hash <= UINT16_MAX)
{
if (hash <= UINT8_MAX) bytes = 1;
else bytes = 2;
}
else bytes = 3;
}
else bytes = 4;
}
else if (hash <= UINT64_MAX)
{
if (hash < 72057594000000000ULL)
{
if (hash < 281474976710656ULL)
{
if (hash < 1099511627776ULL) bytes = 5;
else bytes = 6;
}
else bytes = 7;
}
else bytes = 8;
}
与Thomas Pornin的答案相比,主要使用56位值的速度差异微小(但可测量)。我还没有测试使用__builtin_clzl的解决方案,这可能是可比较的。
__builtin_clzll
会给你更好的性能,因为它最终只需要大约3个汇编指令而没有任何分支。即使在添加了对零的检查后,你最终也只有大约10个指令。 - D.Shawley