Eng*_*eer 7 c c++ bit-manipulation bit-fields
问题说明了一切.
如果我有一个96位字段:
uint32_t flags[3]; //(thanks @jalf!)
Run Code Online (Sandbox Code Playgroud)
考虑到其中的子域可能位于32位边界(例如,从第29位到第35位的字段),我如何最好地访问它?
我需要访问尽可能快,所以我宁愿不将它们作为数组的32位元素进行迭代.
Gru*_*bel 10
STL包含一个用于处理仲裁长度的位域的类:
#include <bitset>
int main() {
const bitset<12> mask(2730ul);
cout << "mask = " << mask << endl;
bitset<12> x;
cout << "Enter a 12-bit bitset in binary: " << flush;
if (cin >> x) {
cout << "x = " << x << endl;
cout << "As ulong: " << x.to_ulong() << endl;
cout << "And with mask: " << (x & mask) << endl;
cout << "Or with mask: " << (x | mask) << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
[这个答案对C有效(对于C++也是如此).]
与平台无关的方法是适当地应用位掩码和位移.
所以要让你的领域从29到35(含):
(flags[1] & 0xF) << 3
| (flags[0] & 0xE0000000) >> 29 // The bitmask here isn't really needed, but I like symmetry!
Run Code Online (Sandbox Code Playgroud)
显然,您可以编写一个类/函数/宏来自动执行此操作.
| 归档时间: |
|
| 查看次数: |
3777 次 |
| 最近记录: |