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?
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)
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
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.
精彩评论