python rgb转整数,将整数转换为RGB值,然后使用Python返回

I have two functions, one to return RGB values from a given Integer, and the other function does the reverse, providing it with RGB values it returns an Integer. I'm testing this by seeing if the integer i convert to RGB turns back from RGB into the original integer value, but I'm getting different values.

def getRGBfromI(RGBint):

blue = RGBint & 255

green = (RGBint >> 8) & 255

red = (RGBint >> 16) & 255

return red, green, blue

def getIfromRGB(rgb):

red = rgb[0]

green = rgb[1]

blue = rgb[2]

print red, green, blue

RGBint = (red<<16) + (green<<8) + blue

return RGBint

the test:

i1 = 2147483647

colr1 = getRGBfromI(i1)

print colr1 # returns (255,255,255)

i2 =getIfromRGB(colr1)

print i1, i2 # returns 2147483647 16777215

To me it seems like the getRGBfromI() is correct and the getIfromRGB() is incorrect, but I may be wrong about that too.

解决方案

Both functions seem to be working fine.

The max value expressed by a 24 bit integer (forget the sign for now) is

mx = pow(2,24)-1 # i.e. 16777215

So

i1 = 2147483647

is higher than mx and

colr1 = getRGBfromI(i1)

correctly gives

(255, 255, 255) # better to view it in hex as 0xFFFFFF

since it cuts out the bits higher than 24 (0xFFFFFF occupies bits from 0 to 23)

Viceversa,

i2 = getIfromRGB(colr1)

correctly gives

16777215

which is the max value you can represent with 24 bits (i.e. the mx above).

If you pour 1.4 litres of water in a 1L bottle, some water will be lost in the overflow.

When you empty the bottle, you will find 1L at max

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值