This is not important and should be quite simple, I just don't understand what I'm doing wrong. The story behind this is that I'm playing with tinyNeoPixel lib on the attiny85, and I'm trying to dive a bit deeper than I need.
This is traditional ANSI C and I'm using a Raspberry Pi3 for this test, but for this case this should be irrelevant. The sizeof(c) on the printf just shows that 'c' is 4 bytes, as expected.
I'm trying to extract the Red, Green, and Blue part of a color that's stored as a 32 bits number
Obviously I'm failing to return the result as a 1 byte value, can same one please tell me how do I do that ? Just casting to (uint8_t) just produces zero.
Thank you.
pi3:~/src$ cat a.c
#include <stdio.h>
typedef unsigned char uint8_t;
typedef unsigned long int uint32_t;
#define Red(x) (x & 0xff000000)
#define Green(x) (x & 0x00ff0000)
#define Blue(x) (x & 0x0000ff00)
void main()
{
uint32_t c;
uint8_t r,g,b;
c=0xffeecc00;
r=Red(c);
g=Green(c);
b=Blue(c);
printf("%d - %08x - %02x %02x %02x\n", sizeof(c), c, r, g, b);
printf("%d - %08x - %02x %02x %02x\n", sizeof(c), c, Red(c), Green(c), Blue(c));
}
pi3:~/src$ gcc a.c -o a
pi3:~/src$ ./a
4 - ffeecc00 - 00 00 00
4 - ffeecc00 - ff000000 ee0000 cc00
The solution is:
#define Red(x) (((x) & 0xff000000) >> 24)
#define Green(x) (((x) & 0x00ff0000) >> 16)
#define Blue(x) (((x) & 0x0000ff00) >> 8)
With this macros this produces
pi3:~/src$ ./a
4 - ffeecc00 - ff ee cc
4 - ffeecc00 - ff ee cc
as it should. Thank you guys.