Search code examples
cbit-fields

How to write a bitfield to an integer value?


I am trying to do this:

typedef struct {
    uint16_t red : 6;
    uint16_t green : 5;
    uint16_t blue : 5;
} color_t

Then I would like to get something like:

color_t clr;
clr.red = 0;
clr.green = 10;
clr.blue = 15;

And write the compound variable clr to an int:

int value = clr; // this does not work

fprintf(draw, "%4X", value);

The reason I am doing this is I want to create colors like orange, purple and so on and draw them on the screen from a file. Inside a file I am writing a color in hex format.

One another thing is that I'd like to do this later in my code:

if (clr == value) { ... }

Or in another words, I'd like to compare the values from struct bitfield and int holding the real hex value of the color.


Solution

  • This is a stand-alone example showing how to use a union to access the value of a struct with bit fields:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct {
        uint16_t red: 6;
        uint16_t green: 5;
        uint16_t blue: 5;
    } color_t;
    
    typedef union {
        uint16_t color_value;
        color_t color_bits;
    } color_helper_t;
    
    int main(void) {
        color_helper_t clr;
    
        clr.color_bits.red = 0;
        clr.color_bits.green = 0;
        clr.color_bits.blue = 15;
    
        uint16_t value = clr.color_value;
    
        printf("%04X\n", value);
    
        if (clr.color_value == value) {
            printf("The values are equal\n");
        }
    
        return 0;
    }
    

    Output

    7800
    The values are equal