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 )
    {
        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/

相关文章:

c++ - 如何在 C++ 中设置 json 库? (微软 Visual Studio )

c++ - 单线程两个进程

具有结构的 C++ 映射

c++ - 升级到 Qt 5.15 后,ListView 委托(delegate)中的父级为空

c++ - 如何使用指定的编译器(例如 GCC)安装 Boost

c++ - 在 win7 上使用 MinGW 6.3.0 构建 boost 1.63.0

c++ - QLibrary - 导入一个类

c++ - 使用 Open Cascade 读取步骤文件

c++ - 结构初始化 vector

c++ - 为什么需要这种明确的范围解析?