Converting back and forth between Hexidecimal Strings and Numbers

Its really convenient for anyone coming from an HTML background that we can now provide colors to Flex using html standard syntax for hexidecimal number (#000000 = black, #ffffff= white, etc).  I've recently been building some tools to convert drawings in the flash player to and from SVG format.  SVG, like HTML, likes to specify hexidecimal numbers with a "#" prefix, but the flash player drawing API needs hexidecimal numbers to be prefixed with "0x"  To help migrate back and forth between hexStrings and AS numbers, I wrote a few static methods, which are working well for me:

package utils {
 public class Colors {
  public static function hexStringToNumber(hexStr:String):Number{
   if(hexStr.length != 7){
    return -1;
   }
   if(hexStr.charAt(0) != "#"){
    return -1;
   }
   var newStr:String = hexStr.substr(1,6);
   var numStr:String = "0x"+newStr;
   var num:Number = Number(numStr);
   return num;
  }
  public static function numToHexString(num:Number):String{
   var hexStr:String = num.toString(16);
   while(hexStr.length < 6){
    hexStr = "0"+hexStr;
   }
   hexStr = "#"+hexStr;
   return hexStr;
  }
 }
}

As you can see, there are 2 methods hexStringToNumber and numToHexString.  These can be used simply like this:

var whiteNum:Number = Colors.hexStringToNumber ("#ffffff");
var whiteStr:String = Colors.numToHexString(16777215);

 

 

Comments
Mike's Gravatar Hi Jeff. Sounds very interesting. I would love to see your Flash Drawing API to SVG ActionScript Class. I have a Flex example where I'm converting a drawing to a PNG and then a SVG, and finally to a PDF, but the tool I'm using (Kvec) for my conversion between a PNG and SVG suffers from a loss in detail and in some cases some color loss. I knew that the Flash native vectors could be directly manipulated into SVG (I did this back in the Flash 7 / AS 2 days), but my AS 3 is not as developed as it needs to be - yet. Do you happen to have any code snippets of what you built for this conversion (native flash drawing to SVG)?
Thanks, Mike www.flexination.info
# Posted By Mike | 2/5/07 12:01 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.001.