Search code examples
carraysavrunionsavr-gcc

Using array of chars as an array of long ints


On my AVR I have an array of chars that hold color intensity information in the form of {R,G,B,x,R,G,B,x,...} (x being an unused byte). Is there any simple way to write a long int (32-bits) to char myArray[4*LIGHTS] so I can write a 0x00BBGGRR number easily?

My typecasting is rough, and I'm not sure how to write it. I'm guessing just make a pointer to a long int type and set that equal to myArray, but then I don't know how to arbitrarily tell it to set group x to myColor.

uint8_t myLights[4*LIGHTS];
uint32_t *myRGBGroups = myLights; // ?

*myRGBGroups = WHITE; // sets the first 4 bytes to WHITE
                      // ...but how to set the 10th group?

Edit: I'm not sure if typecasting is even the proper term, as I think that would be if it just truncated the 32-bit number to 8-bits?


Solution

  • typedef union {
        struct {
             uint8_t    red;
             uint8_t    green;
             uint8_t    blue;
             uint8_t    alpha;
        }          rgba;
        uint32_t   single;
    } Color;
    
    Color    colors[LIGHTS];
    
    colors[0].single = WHITE;
    colors[0].rgba.red -= 5;
    

    NOTE: On a little-endian system, the low-order byte of the 4-byte value will be the alpha value; whereas it will be the red value on a big-endian system.