Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 812
Eric Avatar asked May 14 '09 14:05

Eric


People also ask

What is nibble in C?

A nibble is a four-bit aggregation, or half an octet. There are two nibbles in a byte. Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits). The two nibbles are (0110) and (0100).

Is there a bit type in C?

The minimum size for char is 8 bits, the minimum size for short and int is 16 bits, for long it is 32 bits and long long must contain at least 64 bits. The type int should be the integer type that the target processor is most efficiently working with. This allows great flexibility: for example, all types can be 64-bit.


1 Answers

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;
};
like image 130
mmx Avatar answered Oct 02 '22 07:10

mmx