How to work with bitfields longer than 64 bits?

懵懂的女人 提交于 2019-12-05 04:33:01

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

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

There's no problem with bitfields going over 64 bits. They can be even much larger than yours!

The trouble I see, is that you are accessing members that cross a 32 bits boundary. This is more of an issue. But to be honest, on 64 bits platforms, if you use long long to create your bitfield types, then you only have to be careful on 64 bits boundaries.

If your motivation is to make your accesses "as fast as possible", then think twice before trying to be smarter than the compiler. Nowadays, they can optimize as you're not even aware of. My best recomandation here: keep your code easily readable and understandable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!