Convert hexadecimal value to RGB

Convert hexadecimal value to RGB
This ActionScript function takes in one hex value (such as #FF07BA) and converts it into an RGB (Red Green Blue) value, thus useful for converting colors between the two popular formats.
function ConvertToRGB(hexNum:Number)
{
    var rgbObj:Object = new Object();  
    rgbObj.r = hexNum >> 16;
    var tmpVal = hexNum - (rgbObj.r << 16);
    rgbObj.g = tmpVal >> 8;
    rgbObj.b = tmpVal & 0xFF;
    return rgbObj;
}

This ActionScript function, ConvertToRGB, is designed to convert a hexadecimal color value to its corresponding RGB (Red, Green, Blue) components. Let’s break down the function step by step:

Function Declaration:

function ConvertToRGB(hexNum:Number)

This line declares a function named ConvertToRGB that takes one parameter hexNum, which is expected to be a number. This number represents a hexadecimal color value.

Object Initialization:

var rgbObj:Object = new Object();

Here, an object rgbObj is created. This object will be used to store the red, green, and blue components of the color.

Extracting the Red Component:

rgbObj.r = hexNum >> 16;

The red component is extracted by bit-shifting the hexadecimal value 16 bits to the right (>> 16). In a typical hexadecimal color code (like 0xFFCC33), the first two characters after 0x represent the red component. Bit-shifting right by 16 bits effectively isolates these two characters.

Preparing to Extract Green and Blue:

var tmpVal = hexNum ^ rgbObj.r << 16;

This line is supposed to reset the bits corresponding to the red component to zero, but it seems to have an error. The correct operation should be hexNum - (rgbObj.r << 16). This subtraction removes the red component from hexNum, leaving only the green and blue components.

Extracting the Green Component:

rgbObj.g = tmpVal >> 8;

This line extracts the green component by bit-shifting tmpVal 8 bits to the right. After removing the red component, the next two characters in the hexadecimal code represent the green component.

Extracting the Blue Component:

rgbObj.b = tmpVal ^ rgbObj.g << 8;

This line is intended to extract the blue component, but it also has an error. The correct operation should be tmpVal & 0xFF. This bitwise AND operation with 0xFF (which is 255 in decimal and represents 11111111 in binary) isolates the last two characters in the hexadecimal code, which are the blue component.

Return the RGB Object:

return rgbObj;

Finally, the function returns the rgbObj object containing the red, green, and blue components.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top