Question says it all.
If I have this for a 96-bit field:
uint32_t flags[3]; //(thanks @jalf!)
How do I best go about accessing this, given that my subfields therein may lie over the 32-bit boundaries (eg. a field that runs from bit 29 to 35)?
I need my accesses to be as fast as possible, so I'd rather not iterate over them as 32-bit elements of an array.
The STL contains a class for dealing with bitfields of arbitary length:
#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;
}
}
[This answer is valid for C (and by extension, for C++ as well).]
The platform-independent way is to apply bit-masks and bit-shifts as appropriate.
So to get your field from 29 to 35 (inclusive):
(flags[1] & 0xF) << 3
| (flags[0] & 0xE0000000) >> 29 // The bitmask here isn't really needed, but I like symmetry!
Obviously, you could write a class/function/macro to automate this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With