位数的数据类型大小

问题描述

| 所以我有以下功能
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,8,8 };

  if (depth <= 64)
    return lut[(depth - 1 >> 3) + 1];

  throw std::exception();
}
    ,
return (int) std::pow(2.0,std::ceil((double)depth / 8.0) - 1)
因为它们都是2的幂,所以您只需要找到除法的指数即可。     ,您可以这样做:
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;
}
哪里:
const int d = depth / 8;
简单给出整数除法的结果。 在哪里:
if (d < 1) || (d & (d - 1) != 0) || (d > 8)
检查
d
是否在1到8之间,并且是2的幂。 诀窍是,
d & (d - 1)
表达式对于所有2的幂均返回
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\");
}