我正在寻找最有效的方法来计算存储整数所需的最小字节数而不会丢失精度.
e.g.
int: 10 = 1 byte
int: 257 = 2 bytes;
int: 18446744073709551615 (UINT64_MAX) = 8 bytes;
Run Code Online (Sandbox Code Playgroud)
谢谢
PS这是一个哈希函数,将被调用数百万次
字节大小也不必是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 < …Run Code Online (Sandbox Code Playgroud) 我将一个整数设置为小于其最大值的值,但是收到的错误是它太大了.为什么是这样?这是一个示例程序.
program max_int
integer, parameter :: i32 = selected_int_kind(32)
integer(kind = i32) :: my_int
!The largest integer of this kind
print*, huge(my_int)
!This works
my_int = 100000
!This doesn't, and gives an error.
!my_int = 1000000000000
print*, my_int
end program
Run Code Online (Sandbox Code Playgroud)