Search code examples
c++cbit-manipulationbit-fields

When and why would you use Bitfields in code?


Possible Duplicate:
When is it worthwhile to use bit fields?

I was looking up bitwise operators recently and stumbled upon the concept of the bitfield. It seems interesting and is a very cool concept, but when and/or why would a person use this in their code?

I know it's used quite a bit in embedded systems programming, but why (I can't seem to find anything about why its useful)? Are there any advantages to it? And where are some other places bitfields are useful?


Solution

  • Some uses that immediately come to mind are:

    • implementing communications protocols;
    • storing user data in objects where you have limited space;
    • extending data structures in existing protocols (similar to the above);
    • performing multiple tests in a single operation;