# Format/convert decimal to hexadecimal (or other numeral system)

By | 23 February, 2009

My problem was to convert some calculations from decimal to hexadecimal to be used in a canvas background color. Specifically, convert from CMYK, from a pantone list, to RGB and apply the result to a canvas.

In a different post i will describe the convertion, might be useful for someone.

Flex has a way of converting to several numeral systems. For example, from the manual:

```var myuint:uint = 9; trace(myuint.toString(2)); // output: 1001 - binary system trace(myuint.toString(8)); // output: 11 - octal system```

And to create hexadecimal values, to be used in uint format:

```var r:uint = 250; var g:uint = 128; var b:uint = 114; var rgb:String = "0x" + r.toString(16) + g.toString(16) + b.toString(16); trace(rgb); // 0xfa8072```

All seems well, except when the result in hexadecimal is just one caracter long, so be sure to check and pad it with a zero.
A simple example:

```var r:uint = 8 var rs:String = (r.toString(16).length == 1) ? "0"+r.toString(16) : r.toString(16);```

Breaking it down:

r.toString(16) –> converts the var r to hexadecimal, which equals “8”.

I then check the length of the result and, in case it equals 1, add a “0” to the beginning of the string to pad it.

UPDATE/FIX: As pointed out by Joe (comment below), r.toString(16) converts the decimal number to string representation of a hexadecimal number.

## 2 thoughts on “Format/convert decimal to hexadecimal (or other numeral system)”

1. Joe

Not exactly. A string is not hexadecimal. r.toString(16) converts the decimal number to string representation of a hexadecimal number.

2. 42 Post author

True. I updated the post to reflect your observation. Thanks. :-)