Reputation: 37
Okay, I have a method that I am having a difficult time with returning the desired results. So I made a test result, and it is returning a result that I was not expecting.
Here is an example -->
int color = 0x00FFFF00;
return 0xFF & (color >> 24) | 0xFF & (color >> 16) | 0xFF & (color >> 8);
From what I know, this should return:
0x00FFFF
However, it actually returns:
0x0000FF
Can someone please explain what is happening? I would also like to know how I could properly convert the 32-bit RGBA integer to the 24-bit RGB integer, thank you.
Upvotes: 0
Views: 183
Reputation: 37
I also caught what I did wrong. I was not shifting the red and green elements of the integer cast to match the RGB integer --->
int color = 0x00FFFF00;
// Returns 0x0000FF
return 0xFF & (color >> 24) | 0xFF & (color >> 16) | 0xFF & (color >> 8);
Here is the fixed code --->
unsigned int color = 0x00FFFF00; // Unsigned Integer to avoid shifting the Two's Complement flag into the RGB value as clearlight pointed out.
// Returns 0x00FFFF
return (0xFF & (color >> 24)) << 16 | (0xFF & (color >> 16)) << 8 | 0xFF & (color >> 8);
Upvotes: 1
Reputation: 12625
Try this:
#include <stdio.h>
int main() {
unsigned int x = 0x00FFFF00;
printf("0%8.8x", (x >> 8) & 0x00FFFFFF);
}
$ cc -o shft shft.c
$ ./shft
0x0000ffff
It's better if you make color an unsigned int
,
otherwise you can get the sign bit shifted in from the left, but in this case we're masking off the shifted in bytes, but be careful of that.
Upvotes: 0