472,328 Members | 1,763 Online

# bitshifting help

Okay, so I have a 16 bit positive value (0-65535) representing a color in 565 RGB notation, that is 5 bits for red, 6 bits for green, and 5 bits for blue.

I need to separate the red, green, and blue values out so I may give them to a function that takes red, green, and blue values separately.

So, thinking back to C, I figured I could use bitshifts. But when I do, it appears the bits wrap around. So is this even possible in Python?
Nov 20 '06 #1
8 1586
bartonc
6,596 Expert 4TB
Okay, so I have a 16 bit positive value (0-65535) representing a color in 565 RGB notation, that is 5 bits for red, 6 bits for green, and 5 bits for blue.

I need to separate the red, green, and blue values out so I may give them to a function that takes red, green, and blue values separately.

So, thinking back to C, I figured I could use bitshifts. But when I do, it appears the bits wrap around. So is this even possible in Python?
One way is (off the top of my head)
Expand|Select|Wrap|Line Numbers
1.
2. rgbValue = 65535
3. red = rgbValue & 0xf800 >> 11
4. green = rgbValue & 0x07e0 >> 5
5. blue = rgbValue & 0x001f
6.
I'm sure I'll think of others when the pressure is off.
Nov 20 '06 #2
bartonc
6,596 Expert 4TB
By the way, spacecoyote, welcome to TheScripts! We're glad you found the site and hope that you post often and tell your friends about us.
Nov 20 '06 #3
One way is (off the top of my head)
Expand|Select|Wrap|Line Numbers
1.
2. rgbValue = 65535
3. red = rgbValue & 0xf800 >> 11
4. green = rgbValue & 0x07e0 >> 5
5. blue = rgbValue & 0x001f
6.
I'm sure I'll think of others when the pressure is off.
Unfortunately, that doesn't seem to work :(

If I substitute (for example) the value 43039, r, g, and b still equal 31, so it apparently only works for 65535...
Nov 20 '06 #4
What values are you expecting? 31 is 011111 (5 bits all one).
Hmm...

43039 =
1010100000011111

so:

r=10101=21
g=000000=0
b=11111=31
Nov 20 '06 #5
I see that shifting doesn't work for some reason. I'll research this and get back to you.
The AND part works, so for now you can just divide by the appropriate power of 2
r = c >> 11 works and
b = c & 0x001f works,
g is the tough one...
Nov 20 '06 #6
bartonc
6,596 Expert 4TB
r = c >> 11 works and
b = c & 0x001f works,
g is the tough one...
Boy do I feel foolish. It's operator presidence:
(43039 & 0x07e0) >> 5
Nov 20 '06 #7
Boy do I feel foolish. It's operator presidence:
(43039 & 0x07e0) >> 5
Hooray! It works. Thank you :)
Nov 20 '06 #8
bartonc
6,596 Expert 4TB
Hooray! It works. Thank you :)
You are quite welcome. Post any time.
Nov 20 '06 #9