Actionscript suffers like many other languages from poor string parsing commands. What would take one line of well crafted perl is… a bit more complex here.


public function hex2dec( hex:String ) : String {
	var bytes:Array = [];
	while( hex.length > 2 ) {
		var byte:String = hex.substr( -2 );
		hex = hex.substr(0, hex.length-2 );
		bytes.splice( 0, 0, int("0x"+byte) );
	}
	return bytes.join(" ");
}

private function d2h( d:int ) : String {
	var c:Array = [ '0', '1', '2', '3', '4', '5', '6', '7', '8',
			'9', 'A', 'B', 'C', 'D', 'E', 'F' ];
	if( d > 255 ) d = 255;
	var l:int = d / 16;
	var r:int = d % 16;
	return c[l]+c[r];
}

public function dec2hex( dec:String ) : String {
	var hex:String = "0x";
	var bytes:Array = dec.split(" ");
	for( var i:int = 0; i < bytes.length; i++ )
		hex += d2h( int(bytes[i]) );
	return hex;
}

What do these methods do? Well, hex2dec takes a hexadecimal string (and assumes you have a throwaway prefix of “0x” or “#”) and returns a space-separated list of decimal values. dec2hex does the same thing, but in reverse.

hex2dec("0xF00F04") returns “240 15 4″
dec2hex("240 15 4") returns “0xF00F04″

Also, the method doesn’t much care if you’ve got 6 hex digits or 60.

There are a few optimizations I could make on this code here, but it’s not getting called that frequently anyway. The performance gains in my application would be trivial.

And just by way of warning, this is AS3 code. It’d need a few tweaks to work reliably in AS2 or (shudder) AS1 environments. Actually, I should make a standard boilerplate for here since I’m only ever really going to present AS3.