I need to store a value between 0-15 in C , 4 bits are enough for this. How can I just have a variable of 4 bits? Space is a constraint here
Consider using a char
. Yeah, it's 8-bits, but you can use the bit shift operators (<<
and >>
) to store values in the other 4 bits.
Edit: Per the comments below, an unsigned char
is, in fact, preferable over char
to avoid issues with the sign bit.
You can use a bitfield to store your 4 bits, however, unless you've several of them adjacent in a struct, you won't save any space over storing the value in a byte.
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