gpt4 book ai didi

c++ - 如何确定一个整数需要多少字节?

转载 作者:IT老高 更新时间:2023-10-28 12:55:10 53 4
gpt4 key购买 nike

我正在寻找最有效的方法来计算存储整数所需的最小字节数而不会丢失精度。

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 位 val 的速度差异很小(但可测量)。我也没有使用 __builtin_clzl 测试解决方案,这可以比较。

最佳答案

使用这个:

int n = 0;
while (x != 0) {
x >>= 8;
n ++;
}

这假定 x 包含您的(正)值。

请注意,零将被声明为可编码,因为根本没有字节。此外,大多数可变大小编码需要一些长度字段或终止符来知道编码在文件或流中停止的位置(通常,当您编码一个整数并注意大小时,编码对象中有多个整数)。

关于c++ - 如何确定一个整数需要多少字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2274428/

53 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com