convert Decimal to Hex and back

In Flash (AS3), when you store a colour in a variable, although the 0x specifies an hexadecimal value, the variable will be of type uint (unsigned integer).

Actionscript:
  1. var c:uint = 0xFFFFFF;

This means that Flash, internally, converts the hexadecimal value to decimal.
You can easily verify this by tracing this variable's value:

Actionscript:
  1. trace (c); // 16777215

What if you want to convert this decimal value back to hexadecimal?
You use toString() and pass the parameter 16:

Actionscript:
  1. trace (c.toString(16)); // ffffff

Notice that what you get is a string.
If you want to have 0xFFFFFF instead of ffffff, all it takes is some very simple string manipulation:

Actionscript:
  1. trace("0x" + c.toString(16).toUpperCase()); // 0xFFFFFF

If you want to use this value in Flash, you'll have to cast it to an integer using uint():

Actionscript:
  1. trace (uint("0x" + c.toString(16).toUpperCase())); // 16777215

Here's the complete code:

Actionscript:
  1. var c:uint = 0xFFFFFF;
  2. trace (c);
  3.  
  4. var s:String = "0x" + c.toString(16).toUpperCase();
  5. trace (s);
  6.  
  7. trace (uint(s));

1 comment to convert Decimal to Hex and back

  • helloworlder

    Thanks! I was looking for a simpler way to do this.

    However if you want the typical representation where leading 0s are not dropped, then I’ve modified the script to do so. E.g. you want it to be represented as 0×00AA00 and not 0xAA00.

    var c:uint = 0×00AA00;

    trace (c);
    var s:String = c.toString(16).toUpperCase();

    while(s.length < 6)
    {
    s = "0" + s;
    }

    s = "0x" + s;

    trace (s);

    trace (uint(s));

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>