C++ – Using nibbles (4 bits variables) in windows C/C++


I'm programming network headers and a lot of protocols use 4 bits fields. Is there a convenient type I can use to represent this information?

The smallest type I've found is a BYTE. I must then use a lot of binary operations to reference only a few bits inside that variable.

Best Solution

Since the memory is byte-addressed, you can't address any unit smaller than a single byte. However, you can build the struct you want to send over the network and use bit fields like this:

struct A {
   unsigned int nibble1 : 4;
   unsigned int nibble2 : 4;