This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Packing 12-bit date into int

Hi,
my i have a 12-bit AD-Converter and want to avoid wasting my precious memory space.

Is it possible to put 4k of this 12-bit-word into 1.5k unsigned int (32 bit) variables?

This stuff should be adressable as a kind of ring-buffer.

Think a struct with union should do. But as i'am a relative beginner i'am not sure about the syntax.

Parents Reply Children
  • Yes it is a bit stupid if there is no data type of size n*4 bits, where n is odd.

    If you don't have a 4-bit native data type, then you can't have a union with two nibbles in a byte. If you don't have a 12-bit data type, you can't have a data structure wtih two 12-bit values in three bytes, or 8 12-bit values in a union of 96 bits (3*32-bit).

    If there was no need for an array and your only goal was to store nibbles, then you could use bit fields. That would allow you to hide the masking and shifting and store two nibbles in a byte. But bit fields can't span several integers. And even if n*12 bits did perfectly match the size of an existing integer data type (normally 8, 16, 32, 64, 128, ...), you can not use array addressing to access these bit fields, so there would not be any elegance.

    With a byte array, you could write a #define to set or get an ADC value in the array. However, I'm not too fond of the use of #define to hide code. It has a tendancy to result in a bloody nose somewhere in the future.