Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create 24 bit unsigned integer in C

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.

like image 454
bgarrood Avatar asked Oct 21 '25 19:10

bgarrood


1 Answers

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.

like image 89
S.S. Anne Avatar answered Oct 24 '25 08:10

S.S. Anne