Using logical bit shift for RGB values

I am a bit naive when it comes to bitwise logic, and I have what is probably a simple question ... basically if I have this (this is ActionScript, but can be used in many languages):

var color:uint = myObject.color; var red:uint = color >>> 16; var green:uint = color >>> 8 & 0xFF; var blue:uint = color & 0xFF; 

I was wondering what exactly `& 0xFF 'does for green and blue. I understand what operation AND does, but why is it needed (or a good idea) here?

The source for this code was here: http://alexgblog.com/?p=680

Rate the tips. Alex

+4
source share
1 answer

In RGB, you have 8 bits for Red, 8 bits for Green and 8 bits for Blue. You store 3 bytes in an int that has 4 bytes as follows:

  • Bits from 0-7 (least significant) for Blue.
  • Bits from 8-15 (least significant) for green.
  • Bits 16-23 (least significant) for red.

To extract them for individual values, you need to shift the correct number of bits to put the byte corresponding to the color that you want to extract in the lowest value of the int byte, and then put the rest of the int at 0 so that only that byte value. The last part is performed using the AND operation with mask 0xFF. And leaves a single int byte, where it is applied with the same value, leaving the remaining bytes at 0.

Here's what happens:

 var color:uint = myObject.color; 

You have a color variable: 0x00RRGGBB

 var red:uint = color >>> 16; 

The color on the right side of 16 bits results in: 0x000000RR, which results in a red value.

But for:

 var green:uint = color >>> 8 & 0xFF; 

After a right shift of color of 8 bits, it leaves this result 0x0000RRGG, but here we only need the GG bit, so we use the AND operation with the mask 0xFF or, to be more clear, 0x000000FF, since you show know AND, leave the old bit, where the mask is 1, and the zeros there are 0, so the result is 0x0000RRGG & 0x000000FF = 0x000000GG , which is the value for green. The same applies for highlighting a blue value.

+13
source

All Articles