如何通过位掩码存储和检索3位数字
How to store and retrieve 3-Bit number via bitmask?
假设我有一个位掩码
enum ExampleMask
{
Attribute1 = 1 << 1,
Attribute2 = 1 << 2,
...
Attribute27 = 1 << 27
}
因此,我已经使用了32个可用位中的27个。
除了使用位掩码的标志之外,我现在还希望能够存储和检索一个3位无符号整数。
例如:
// Storing values
int mask = Attribute2 | Attribute6 | Attribute18; // Saving some attributes
int mask |= ???? // How to save the number 8?
// Retrieving values
if(mask & Attribute2) do something...;
if(mask & Attribute6) do something...;
int storedValue = ???? // How to retrieve the 8?
基本上,我想在我的比特掩码中保留3个比特,以在那里保存0-8之间的数字
感谢您抽出时间阅读并提供帮助。
您可以将值上移到未使用的位,例如
存储值:
mask |= val << 28;
检索值:
val = mask >> 28;
注意,mask
实际上应该是unsigned
,以避免在移位时传播符号位。如果由于某种原因必须使用带符号的int,那么在检索val
时应该添加一个额外的屏蔽操作,例如
val = (mask >> 28) & 0x0f;
相关文章:
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 使用VerQueryValue检索应用程序的文件描述
- C / C++ 移位/偏移/向左或向右移动位图?
- 对字符串进行位操作
- 如何在24位SDL_Surface上设置像素的颜色
- 将浮动的heightmap数组导出为16位原始值
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- C++Union/Struct位域的实现和可移植性
- 如何在QByteArray中放置和检索位字段而不会感到痛苦?
- Qt 错误:QSqlQuery::value:尝试从表中检索统计信息时未定位在有效记录上 (QComboBox)
- 32位到64位:LNK2019错误,如何检索相关信息
- 存储和检索位字段中的有符号值
- 如何在C++中以编程方式检索 64 位进程的详细信息
- 无法在OpenGL碎片着色器中正确检索16位整数
- 如何从wow64进程中检索特定内核对象的64位地址
- 如何通过位掩码存储和检索3位数字
- 为遗传算法分配和检索逐位内存值
- 32位办公环境vba应用中uint64值的检索
- 如何保存(和检索)文件的位序列