I am working on an embedded application where RAM is extremely tight. For this purpose I need to create a 24 bit unsigned integer data type. I am doing this using a struct:
typedef struct
{
uint32_t v : 24;
} uint24_t;
However when I interrogate the size of a variable of this type, it returns "4", i.e.:
uint24_t x;
x.v = 0;
printf("Size = %u", sizeof(x));
Is there a way I can force this variable to have 3 bytes?
Initially I thought it was because it is forcing datatypes to be word aligned, but I can for example do this:
typedef struct
{
uint8_t blah[3];
} mytype;
And in that case the size comes out at 3.
A comment by João Baptista on this site says that you can use #pragma pack. Another option is to use __attribute__((packed)):
#ifndef __GNUC__
# define __attribute__(x)
#endif
struct uint24_t { unsigned long v:24; };
typedef struct uint24_t __attribute__((packed)) uint24_t;
This should work on GCC and Clang.
Note, however, that this will probably screw up alignment unless your processor supports unaligned access.
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