I need to define a struct which has data members of size 2 bits and 6 bits.
Should I use char
type for each member?Or ,in order not to waste a memory,can I use something like :2
\ :6
notation?
how can I do that?
Can I define a typedef for 2 or 6 bits type?
The size of the short type is 2 bytes (16 bits) and, accordingly, it allows expressing the range of values equal to 2 to the power 16: 2^16 = 65 536.
In any programming language, size of a data type is means how many binary bits are used to store an instance of that type. So, size of int data type is 2 bytes means that the compiler uses two bytes to store a int value.
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, unless you're having to comply with packed data external to your application, or you're in a very memory constrained situation, this sort of memory saving is not usually worth it. You'll find your code is a lot faster if it's not having to pack and unpack data all the time with bitwise and bitshift operations.
Also keep in mind that use of any type other than _Bool
, signed int
or unsigned int
is an issue for the implementation. Specifically, unsigned char
may not work everywhere.
It's 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 don't think you can be sure that the compiler will pack this into a single byte, though. Also, you can't know how the bits are ordered, within the byte(s) that values of the the struct type occupies. It's often better to use explicit masks, if you want more control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With