Integer to byte conversion

情到浓时终转凉″ 提交于 2019-12-23 21:45:50

问题


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?


回答1:


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)



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2562308/integer-to-byte-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!