2 bit variable

I need to define a structure that has 2 bits and 6 bits data elements. Should I use char type for each member? Or, so as not to waste memory, is it possible to use something like :2 \ :6 notations? How can I do it? Can I define a typedef for type 2 or 6 bits?

+4
source share
3 answers

You can use something like:

 typedef struct { unsigned char SixBits:6; unsigned char TwoBits:2; } tEightBits; 

and then use:

 tEightBits eight; eight.SixBits = 31; eight.TwoBits = 3; 

But, to be honest, if you donโ€™t need to follow the packed data external to your application, or if you are in a situation with limited memory, this kind of memory saving is usually not worth it. You will find that your code is much faster if it does not need to constantly pack and unpack data using bitwise and bit-operations.


Also keep in mind that using any type other than _Bool , signed int or unsigned int is an implementation issue. In particular, unsigned char may not work everywhere.

+7
source

It is probably best to use uint8_t for something like this. And yes, use bit fields :

 struct tiny_fields { uint8_t twobits : 2; uint8_t sixbits : 6; } 

I do not think you can be sure that the compiler will pack this in one byte. Also, you cannot know how the bits are ordered, in bytes (bytes), which occupy values โ€‹โ€‹of type struct. It is often better to use explicit masks if you want more control.

+5
source

Personally, I prefer shift operators and some macros over bit fields, so thereโ€™s no magic left for the compiler. This is a common practice in the embedded world.

 #define SET_VAL2BIT(_var, _val) ( (_var) | ((_val) & 3) ) #define SET_VAL6BIT(_var, _val) ( (_var) | (((_val) & 63) << 2) ) #define GET_VAL2BIT(_var) ( (_val) & 3) #define GET_VAL6BIT(_var) ( ((_var) >> 2) & 63 ) static uint8_t my_var; <...> SET_VAL2BIT(my_var, 1); SET_VAL6BIT(my_var, 5); int a = GET_VAL2BIT(my_var); /* a == 1 */ int b = GET_VAL6BIT(my_var); /* b == 5 */ 
+1
source

All Articles