所以我有以下功能:
static int calcDTSize( int depth )
{
if ( depth <= 8 )
{
return 1;
}
if ( depth <= 16 )
{
return 2;
}
if ( depth <= 32 )
{
return 4;
}
if ( depth <= 64 )
{
return 8;
}
throw std::exception( "Invalid bit count" );
}
计算指定位数所需的数据类型的大小。本来我只有:
return ( (int) std::ceil( (double) depth / 8.0 ) );
然而,在我所知道的大多数机器上,没有 3 个字节长的数据类型。
我确信必须有一种没有 if 语句的更简洁的计算方法,但我想不出怎么做。
谁有更好的解决方案?
最佳答案
除以 8 并四舍五入到最接近的 2 的幂。
考虑到输入是有限的并且信息是完全静态的,我可能会把它放在一个查找数组中然后做
if (depth <= 64)
return lut[depth];
throw std::exception( "Invalid bit count" );
如果你不想在 lut 中有 64 个条目,你可以这样做
static int calcDTSize( int depth )
{
static int lut[] = { 0, 1, 2, 4, 4, 8, 8, 8, 8 };
if (depth <= 64)
return lut[(depth - 1 >> 3) + 1];
throw std::exception();
}
关于c++ - 位数的数据类型大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6097543/