Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using logical bitshift for RGB values

I'm a bit naive when it comes to bitwise logic and I have what is probably a simple question... basically if I have this (is ActionScript but can apply 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 the `& 0xFF' is doing to green and blue. I understand what an AND operation does, but why is it needed (or a good idea) here?

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

Appreciate the tips. Alex

like image 729
Alex Avatar asked Dec 10 '22 09:12

Alex


1 Answers

In RGB you have 8 bits for Red, 8 bits for Green and 8 bits for Blue. You are storing the 3 bytes in an int, which has 4 bytes in this way:

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

To extract them to separate values you need to right shift the correct number of bits in order to put the byte corresponding to the color you want to extract in the least significant byte of the int, and then put the rest of the int in 0 so as to let that byte value only. The last part is done by using the AND operation with mask 0xFF. The AND leaves the only byte of the int where it is applied with the same value, leaving the rest bytes in 0.

This is what happens:

var color:uint = myObject.color;

You have the color variable like this: 0x00RRGGBB

var red:uint = color >>> 16;

Right-shifting 16 bits color results in: 0x000000RR, resulting in the red value.

But for:

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

After right-shifting color 8 bits it leaves this result 0x0000RRGG, but here we only need the GG bits left so we apply the AND operation with the mask 0xFF or to be more clear 0x000000FF, as you show know AND leaves the old bits values where the mask is 1 and zeros there the mask is 0, so the result of doing 0x0000RRGG & 0x000000FF = 0x000000GG which is the value for green. The same is applied to extract the blue value.

like image 120
Santiago Alessandri Avatar answered Jan 15 '23 21:01

Santiago Alessandri