Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with bitfields longer than 64 bits?

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.

like image 465
Engineer Avatar asked Nov 15 '11 15:11

Engineer


2 Answers

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;
  }
}
like image 114
Grumbel Avatar answered Sep 23 '22 19:09

Grumbel


[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.

like image 43
Oliver Charlesworth Avatar answered Sep 22 '22 19:09

Oliver Charlesworth