Shift Operators

So i have a color in hex:
int color = 0x123456;
I want to separate the the rgb channels with this:
1
2
3
int r = color <<8>>24;
int g = color <<16>>24;
int b = color <<24>>24;

It works for 0x123456 but not for 0xFFFFFF because i get trailing Fs(r = 0xFFFFFFFF). Why is that?
as you have written it - color is a signed integer. Shifting it to the left
as in color <<16 can cause it to take on a negative value.
shifting a value to the right like color >> 24 does someting called signed extension -
which means that all the bits to the left of the shift will take on the the value of the
sign bit - which means that if color became negative when it was shifted to the left - it will
be backfilled with 1 bits when shifted right (that is to say it will stay neagtive).

You will also have that problem with values other than 0xFFFFFFFF

You can make color an unsigned int that will cure the problem (when shifted right the
value will be backfilled with 0 bits instead of 1 bits.


Or this other method will work regardless of whether color is unsigned int or signed int
1
2
3
4
int color = 0xaabbcc;
int rrr = color >>16 & 0xff;
int ggg = color >> 8 & 0xff;
int bbb = color & 0xff;
Last edited on
brilliant! thank you!
Topic archived. No new replies allowed.