位数的数据类型大小

Datatype size for number of bits

本文关键字:数据类型      更新时间:2023-10-16

所以我有以下函数:

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();
}
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) 表达式返回 0 对于 2 的所有幂,否则返回非零。

此代码测试(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");
}