john-bright john-bright - 3 years ago 242
Python Question

Obtaining RGB colors

So I was looking how to get a list of RGB colors depending on a desired total of colors to retrieve and I found this piece of code. And there's a part that I can't understand, I already read the notes where the ">>" and "&" operators are bitwise operators but I can't fully understand what they are doing.

Can anybody help me on understanding the part where the colors values
are been assigned?

def getDinstinctRGBColorsList(desiredColors)
availableColors = 16000000
inc = availableColors/desiredColors
colorsList = {}
RGB = 0
count = 0
while count <= desiredColors:
RGB = RGB+inc
colorBlue = RGB & 255
colorGreen = (RGB >> 8) & 255
colorRed = (RGB >> 16) & 255
colorsList[count] = str(colorRed) + "," + str(colorGreen) + "," + str(colorBlue)
count += 1
return colorsList

Answer Source

See BitwiseOperators and What are bitwise shift (bit-shift) operators and how do they work?.

From the code you posted, it looks like RGB contains 24 bits of color information: 8 bits for red, 8 bits for green, and 8 bits for blue with the red data in the left most 8 bits, the green data in the middle 8 bits, and the blue data in the right most 8 bits.

Imagine the bits of RGB look like 0brrrrrrrrggggggggbbbbbbbb where r is a bit for the red value, g is a bit for the green value, and b is a bit for the blue value.

Note that 255 in binary is 0b11111111 (8 set bits).

colorGreen = (RGB >> 8) & 255 is extracting the middle 8 bits that represent green using >> (right shift) and & (bitwise and):

0brrrrrrrrggggggggbbbbbbbb >> 8 yields 0b00000000rrrrrrrrgggggggg

Note how the bits for green are now the left-most 8 bits. However, the bits for red are still present.

0b00000000rrrrrrrrgggggggg & 0b00000000000000001111111 yields 0b0000000000000000gggggggg

Note how only the bits for green remain.

Edit: This is a simplification. In Python, >> is an arithmetic shift, not a logical shift. An arithmetic shift preserves sign. See [What are bitwise shift (bit-shift) operators and how do they work?] for a more detailed explanation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download