I have a piece of code that I found when trying to get pixel values from an image, and I don’t quite understand it,
red = (rgb & 0x00ff0000) >> 16;
I understand that it’s adding 1 to the value if red colour is there, and I think the 0x00ff0000 bit is a hexidecimal value for red, and the >> shifts 16 bits to the right.
What is the explanation?
This is extracting the red component from a number that (one would presume) represents a color in aRGB.
First:
…uses bitwise and to zero all bits of
rgbexcept those from the byte containing the red component (the third most significant byte). Then, that value is shifted right 16 places (using>> 16), so that it occupies the right-most byte, the value of which is then assigned tored.For example, assume you’ve got an
intrepresenting vivid cyan:Then, this:
Prints:
…which is the decimal value for hex
0x12(from the red position incolorabove).Similarly, you can get the values of the green and blue components with the following: