convert Integers to RGB values and back with Python

被刻印的时光 ゝ 提交于 2019-11-30 07:19:55

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

There's nothing wrong with your code. The values are different, because you are giving 2147483647 as input, which, translated to hexadecimal, gives 0x7FFFFFFF as an output. On the other hand, 16777215 is 0xFFFFFF in hexadecimal, so you understand there is nothing wrong with your code actually, apart from the fact that you are giving such a big decimal number as an input.

You can test this if you type:

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