Search code examples
c++cintegerpacking

unused memory using 32 bit integer in C


I have the folowing struct of integers (32 bit environment):

struct rgb {
    int r;
    int g;
    int b;
};

Am I correct in saying that, since rgb component values (0-255) only require 8-bits(1 byte) to be represented, I am only using 1 byte of memory and leaving 3 bytes unused for each component?

Also, if I instead did the following:

struct rgb{
    unsigned int r:8;
    unsigned int g:8;
    unsigned int b:8;
};

Assuming that what I said above is correct, would using this new struct reduce the number of unused bytes to 1?


Solution

  • I would use unsigned char, which is exactly what you need. Like

    #ifndef BYTE
    #define BYTE unsigned char
    #endif
    
    struct rgb
    {
        BYTE r;
        BYTE g;
        BYTE b;
    };
    

    But to answer your question - yes, it does reduce the number of bytes to 1 for each field.

    Anyway, the struct will probably be with size of 4B, because of the alignment (but these are details and it's completely platform specific) removed, thanks to @JimBuck's comment