# How To Bitshift Properly

• 07-26-2009
pobri19
How To Bitshift Properly
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:

Code:

```red = -86 green = -24 blue = 19```
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?!

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; }```
• 07-26-2009
lattica
Try changing int to unsigned int everywhere, and %d to %u.
• 07-26-2009
pobri19
Yeah that worked. Is that because with signed integers the first or last bit is used to indicate whether the number is negative or not?
• 07-26-2009
lattica
Yes. The left most bit indicates the sign and when right shifting, the word may be filled with whatever the bit was--though, I think that's implementation defined.
• 07-26-2009
BEN10
Quote:

Originally Posted by lattica
I think that's implementation defined.

Yes, it is. Right shifting a signed integer is implementation defined.