which one is better to use, unsigned char or unsigned int and why?
unsigned int
The following is not portable and its consideration should be set aside.
// Only portable bit field types are _Bool, signed int, unsigned int
// This is not portable.
struct data{
unsigned char a:3;
unsigned char b:4;
};
That leaves OP alternative
struct data{
unsigned int a:3;
unsigned int b:4;
};
Which one is better to use for memory allocation and why?
If minimal memory is primary goal, do not use a bit field. Use the minimal integer type: unsigned char
in this case. Add functions or defines to get and set.
void data_a_set(unsigned char *data, unsigned a) {
*data = *data & ~7u | a & 7u;
}
unsigned data_a_get(unsigned char data) {
return data & 7u;
}
// or for a more generic approach
#define B_BITS_PRIOR 3 /* sum of all previous bit widths */
#define B_BITS 4
#define MASK(w,p) (((1u << (w)) - 1) << (p))
void data_b_set(unsigned char *data, unsigned b) {
*data &= ~MASK(B_BITS, B_BITS_PRIOR);
*data |= MASK(B_BITS, B_BITS_PRIOR) & (b << B_BITS_PRIOR);
}
unsigned data_b_get(unsigned char data) {
return (data & MASK(B_BITS, B_BITS_PRIOR) >> B_BITS_PRIOR;
}
For types wider than unsigned
, small changes needed to insure wider and and shift operations.
unsigned char
could be wrapped in a struct
if a unique type is needed.
struct data {
unsigned char ab;
}