Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i represent bit info in C?

Tags:

c

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

like image 319
Laz Avatar asked Aug 07 '10 06:08

Laz


2 Answers

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.

like image 116
kbrimington Avatar answered Sep 17 '22 16:09

kbrimington


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.

like image 33
Will A Avatar answered Sep 18 '22 16:09

Will A