Using unions to simplify casts
Posted
by Steven Lu
on Stack Overflow
See other posts from Stack Overflow
or by Steven Lu
Published on 2010-05-20T18:45:42Z
Indexed on
2010/05/20
18:50 UTC
Read the original article
Hit count: 167
I realize that what I am trying to do isn't safe. But I am just doing some testing and image processing so my focus here is on speed.
Right now this code gives me the corresponding bytes for a 32-bit pixel value type.
struct Pixel {
unsigned char b,g,r,a;
};
I wanted to check if I have a pixel that is under a certain value (e.g. r, g, b <= 0x10
). I figured I wanted to just conditional-test the bit-and of the bits of the pixel with 0x00E0E0E0
(I could have wrong endianness here) to get the dark pixels.
Rather than using this ugly mess (*((uint32_t*)&pixel))
to get the 32-bit unsigned int value, i figured there should be a way for me to set it up so I can just use pixel.i
, while keeping the ability to reference the green byte using pixel.g
.
Can I do this? This won't work:
struct Pixel {
unsigned char b,g,r,a;
};
union Pixel_u {
Pixel p;
uint32_t bits;
};
I would need to edit my existing code to say pixel.p.g
to get the green color byte. Same happens if I do this:
union Pixel {
unsigned char c[4];
uint32_t bits;
};
This would work too but I still need to change everything to index into c
, which is a bit ugly but I can make it work with a macro if i really needed to.
© Stack Overflow or respective owner