Hi, I'm trying to do some simple bitshifting using bitwise operators. I cannot get it to work as desired. The blue color gets printed as it should be (19), but the rest are different, this is the output:
I can't seem to see what I'm doing wrong. When I'm printing the values I shift the bits to the right first to clear the upper bits, then shift it to the bottom. I just noticed that if I use a number up to 128 (not including 128) it works fine. If I use 128 it prints -128, and anything above 128 it prints random garbage. Now, a single byte can store up to 255, so why is it limiting me to 128?!Code:red = -86
green = -24
blue = 19
Surely it's something simple I'm just missing... Or something I'm doing wrong. Ok thanks, here's the code:
Code:#include <cstdio>
int RgbToInt(int r, int g, int b);
int main(void) {
int res = RgbToInt(170, 232, 19);
printf("red = %d\n", (res >> 24));
printf("green = %d\n",((res << 8) >> 24));
printf("blue = %d\n", ((res << 16) >> 24));
}
int RgbToInt(int r, int g, int b) {
int rgb = ((r << 24) | (g << 16) | (b << 8));
return rgb;
}