tags:

views:

144

answers:

3

Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python?

+2  A: 

You can bitwise & with 0xff to get the first byte, then shift 8 bits and repeat to get the other 3 bytes.

Edit: For colors, you know you need the least significant three bytes. So, you can use a nicer approach:

r = num & 0x0000ff
g = (num & 0x00ff00) >> 8
b = (num & 0xff0000) >> 16
Justin Ardini
In order to just pull out the bytes for each color, going with msw's approach will be simpler. I'll leave this post as a general approach to pulling out the bytes.
Justin Ardini
This way, all bytes except the first one becomes 0. I.e. if I shift it.
quano
You would need to store the intermediate results in variables. Go with msw's solution.
Justin Ardini
+6  A: 

Use bitwise mathematical operators, the "bytes" are already there:

def int_to_rgb(n):
    b = (n & 0xff0000) >> 16
    g = (n & 0x00ff00) >> 8
    r = (n & 0x0000ff)
    return (r, g, b)
msw
Thanks, this did the trick!
quano
A: 

Here's an optimisation suggestion that applies in any language, and doesn't harm legibility.

Instead of this:

b = (n & 0xff0000) >> 16
g = (n &   0xff00) >> 8
r = (n &     0xff)

use this:

b = (n >> 16) & 0xff
g = (n >>  8) & 0xff
r =  n        & 0xff

Two reasons:

Having fewer constants is not slower, and may be faster.

Having smaller constants is not slower, and may be faster -- in a language like C, a shorter machine instruction may be available; in a language like Python, the implementation is likely to pool small integers.

John Machin