4-bit integer

Is it possible to declare a four bit integer with 16 possible values. I know you can create 8-bit using uint8 from stdint.h

Does anyone know how to do this? I need a 4 bit integer because i'm working on a project with very strict memory constraints and I should be able to cut down on memory usage considerably if I can fill my arrays with 4 bit integers.
The smallest amount of allocatable space for a variable in C is 1 byte.

If these variables will be part of a struct, you can use bitfields:

1
2
3
4
struct foo
{
  unsigned a:4;  // <- 4 bits wide only
};


However note that if you do this, the structure itself will be padded up to at least the next byte (ie, the 'foo' struct will be 1 byte or larger, even though 'a' is only 4 bits). You can save space this way if you have several variables inside the same struct. Otherwise it isn't very useful.


Other than that, the only way to do it would be to simulate it. If you need an array of 100 4-bit vars, make an array of 50 8-bit vars and treat the high/low 4 bits as if they were different vars.


Of course while you save on memory with these techniques, you somewhat suffer in performance.
Assume char datatype is 8 bits, then you can make use of that to store two 4 bit integer. Now the tricky part is to read/write to this char datatype. I would presume you may want to create a class or a set of functions to help manipulation of a char as if it consist of two 4 bit integer.

Basically you use the built-in bitwise operator to play around with the char to extract the different 4 bit integer values inside.
Topic archived. No new replies allowed.