Recipe 3.3 Decoding an RGB Value

3.3.1 Problem

You want to extract the red, green, and blue components from an RGB value returned by Color.getRGB( ).

3.3.2 Solution

Use the bitshift right and bitwise AND operators.

3.3.3 Discussion

You can extract the red, green, and blue components from the single RGB value returned by Color.getRGB( ) using the bitshift right (>>) and bitwise AND (&) operators. You can extract one or more of the colors individually as follows:

```// Create the Color object.
my_color = new Color(myMovieClip);

// Get the current RGB color.
rgb = my_color.getRGB(  );

// rgb contains an RGB color value in decimal form, such as 14501017 (rosy pink),
// which is stored internally as its hex equivalent, such as 0xDD4499.
red   = (rgb >> 16);
green = (rgb >> 8) & 0xFF;
blue  =  rgb & 0xFF;```

Although displayed as a decimal number, remember that each color is stored internally in its hexadecimal form: 0xRRGGBB. For example, the color value 14501017 (which is rosy pink) is stored internally as 0xDD4499. In this format, it is easy to see that the red component is DD in hex (221 in decimal), the green component is 44 in hex (68 in decimal), and the blue component is 99 in hex (153 in decimal).

The preceding transformation effectively separates a 24-bit value into its three 8-bit components (the leftmost eight bits represent red, the middle eight bits represent green, and the rightmost eight bits represent blue). The bitshift right operator is used to shift the eight bits of interest to the rightmost position. Using the bitwise AND operator with 0xFF retains the rightmost eight bits only, effectively masking off any unwanted bits on the left.

In practice, it is often easier to use Color.getTransform( )?in which the red, green, and blue components are returned as separate properties of a transform object?to determine a clip's color. Furthermore, getTransform( ) also returns the alpha value for a color, which getRGB( ) does not.