位数的数据类型大小
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");
}
相关文章:
- 防止主数据类型C++的隐式转换
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在C++中打印指向不同基元数据类型的指针的内存地址
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何计算数据类型的范围,例如int
- C++中数据类型修饰符的顺序
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 特定数据类型的模板类
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 如何获取C++字符数据类型的地址
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- 构造智能点数据类型以及普通数据类型的通用方法
- 如何使映射键具有两种不同的数据类型?
- 数据类型"struct seq<0, 1, 2>{}"含义是什么?
- 如何在不破坏现有应用程序的情况下更改 API 中 stl 容器的数据类型?
- Static_cast转换为错误的数据类型,但结果仍然正确?
- 使用 Boost.Spirit 解析具有混合数据类型的 OBJ 文件?