How to work with bit fields longer than 64 bits?

The question says it all.

If I have this for a 96 bit field:

uint32_t flags[3]; //(thanks @jalf!)

What is the best way for me to access this, given that my subfields in it can lie above 32-bit boundaries (for example, a field that runs from bits 29 to 35)?

I need my calls to be as fast as possible, so I won’t go through them as 32-bit elements of the array.

+5
source share
3 answers

[This answer is valid for C (as well as an extension for C ++).]

A platform independent method is to apply bit masks and bit shifts as needed.

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!

, // .

+4

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;
  }
}
+6

, 64 . !

, , , , 32 . . , , 64- , long long , 64 .

If your motivation is to make your access "as fast as possible," think twice before trying to be smarter than the compiler. Currently, they can optimize what you don’t even suspect. My best recommendation is here: keep your code easy to read and understand.

-1
source

All Articles