as3 dec <-> hex

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.

[as3]
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;
}
[/as3]

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 04") 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.

update – may 7, 2008

It has come to my attention that people keep stumbling across this old post. While I don’t have the time or interest to optimize these functions for real environments in any of the several ways they could be improved… I figure I’d take a moment for the benefit of those who are probably just looking for the quick answer.

The easiest way of getting a hex string from an int value is to call its toString() method with a radix argument of 16. Likewise, you can request any integer base from 2 to 36. Results use lower-case letters when outputting in a base higher than ten.

240.toString(16) returns “f0”.
240.toString(8) returns “360”.

2 thoughts on “as3 dec <-> hex”

  1. Nice Work,

    Problem with the toString Function are the missing leading zeros.

    e.g.

    you need them if you wanna build a stylesheet an want do convert a color (256) to hex. result with toString is 0xff instead of 0x0000ff

    greetz,
    simon

Leave a Reply

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