Actionscript color conversion: RGB to HEX (kind of)

I ran across a problem today where I wanted to generate random colors in Actionscript. Naturally my first step was to generate a random number for the red, green and blue between 0-255:

var red:Number = Math.random() * 255;
var green:Number = Math.random() * 255;
var blue:Number = Math.random() * 255;

Now I have each color, but I need to combine them so Flash can use it. You may or may not know this but Flash doesn’t care if you give a hexidecimal or decimal number as a color, for example:

var fmt:TextFormat = new TextFormat;

// these 2 lines are identical
fmt.color = 0xFF0000; // HEX, aka 'base16', aka 'radix 16'
fmt.color = 16711680; // DEC, aka 'base10', aka 'radix 10'

Don’t believe me? Try this:

trace(16711680 == 0xFF0000); // true

That having been said - you still can’t specify the Red, Green and Blue in decimal form without combining them. To convert all three colors to one decimal number you need to look at a HEX color first:

RRGGBB <-- two digits for each color.
.....10000 <-- Red
.........100 <-- Green
.............1 <-- Blue

The red is in the 10000’s place, the green is in the 100’s and the blue is in the 1’s place. In HEX you can multiply the Red by 10000, the Green by 100 and the Blue by 1 to get the end product; but we are in decimal. No problem - just convert the 10000,100,1 from HEX to DEC - I’ll save you some time: 0x10000 = 65536, 0x100 = 256, 0x1 = 1. That’s it! Just multiply each color by its number and you’ve got a Flash/Actionscript friendly number.

function rgb2col(red:Number,green:Number,blue:Number){
	// input:   red, green and blue DEC colors (i.e. 255,0,0)
	// returns: decimal color (i.e. 16711680)
	return((red * 65536) + (green * 256) + (blue));
}

If you would like to see the decimal color in the traditional hexidecimal form you can use this function I came up with to convert it for you:

function decColor2hex(color:Number){
	// input:   (Number) decimal color (i.e. 16711680)
	// returns: (String) hex color (i.e. 0xFF0000)
	colArr = color.toString(16).toUpperCase().split('');
	numChars = colArr.length;
	for(a=0;a<(6-numChars);a++){colArr.unshift("0");}
	return('0x' + colArr.join(''));
}

Putting it all together we have a simple, yet complete, random color generator:

function randColor(){
	var red:Number = Math.random() * 255;
	var green:Number = Math.random() * 255;
	var blue:Number = Math.random() * 255;
	return(rgb2col(red,green,blue));
}
function rgb2col(red,green,blue){
	return((red * 65536) + (green * 256) + (blue));
}

stevekamerman

COO @scientiamobile