C++ 位数的数据类型大小
所以我有以下功能:C++ 位数的数据类型大小,c++,C++,所以我有以下功能: static int calcDTSize( int depth ) { if ( depth <= 8 ) { return 1; } if ( depth <= 16 ) { return 2; } if ( depth <= 32 ) { return 4; } if ( depth <= 64 ) {
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" );
}
然而,在我所知道的大多数机器上,没有3字节长的数据类型
我确信一定有一种更简洁的方法来进行计算,而不使用if语句,但我想不出该怎么做
谁有更好的解决办法
return (int) std::pow(2.0, std::ceil((double)depth / 8.0) - 1)
因为它们都是2的幂,所以你只要找到带除法的指数
因为它们都是2的幂,所以你只需找到带除法的指数。除以8,然后四舍五入到最接近的2的幂 考虑到输入是有限的,信息是完全静态的,我可能会把它放在一个查找数组中,然后
if (depth <= 64)
return lut[depth];
throw std::exception( "Invalid bit count" );
if(深度除以8,四舍五入到最接近的2次方
考虑到输入是有限的,信息是完全静态的,我可能会把它放在一个查找数组中,然后
if (depth <= 64)
return lut[depth];
throw std::exception( "Invalid bit count" );
if(depth您可以执行以下操作:
static int calcDTSize( int depth )
{
const int d = depth / 8;
if (d < 1) || (d & (d - 1) != 0) || (d > 8)
throw std::exception("Invalid bit count");
return d;
}
简单地给出整数除法的结果
地点:
if (d < 1) || (d & (d - 1) != 0) || (d > 8)
如果(d<1)| |(d&(d-1)!=0)| |(d>8)
检查d
是否介于1和8之间,并且是2的幂
诀窍是d&(d-1)
表达式返回0
,否则返回非零。您可以执行以下操作:
static int calcDTSize( int depth )
{
const int d = depth / 8;
if (d < 1) || (d & (d - 1) != 0) || (d > 8)
throw std::exception("Invalid bit count");
return d;
}
简单地给出整数除法的结果
地点:
if (d < 1) || (d & (d - 1) != 0) || (d > 8)
如果(d<1)| |(d&(d-1)!=0)| |(d>8)
检查d
是否介于1和8之间,并且是2的幂
诀窍是d&(d-1)
表达式返回0
,否则返回非零。此代码测试(1)大于最大大小的值,(2)无效的3字节数据大小和(3)不是8的倍数的值:
static int calcDTSize( int depth)
{
if ( (depth <= 64) && (depth != 24) && (depth % 8 == 0) )
return depth / 8;
else
throw std::exception("Invalid bit count");
}
static int-calcDTSize(int-depth)
{
如果((深度此代码测试(1)大于最大大小的值,(2)无效的3字节数据大小和(3)不是8的倍数的值:
static int calcDTSize( int depth)
{
if ( (depth <= 64) && (depth != 24) && (depth % 8 == 0) )
return depth / 8;
else
throw std::exception("Invalid bit count");
}
static int-calcDTSize(int-depth)
{
如果((深度