tigra
Administrator
Posts: 1907
Registered: 6/17/2002
Location: US, CO
Member Is Offline
|
| posted on 8/2/2007 at 06:32 PM |
|
|
JavaScript to convert Hex to Decimal Numbers
Today I stumbled upon the need to convert hex color codes to their decimal values. I found a lot of samples where people exercised their algorithmic
skills, some are good, some not. Here is my JavaScript specific solution:
| Code: |
function hex2num (s_hex) {
eval("var n_num=0X" + s_hex);
return n_num;
}
|
In my case validation wasn't needed, but generally it's a good idea. With the input validation the code look like:
| Code: |
var re_hexNum = /^[\da-f]+$/i;
function hex2num (s_hex) {
if (!re_hexNum.exec(s_hex))
return alert ('error');
eval("var n_num=0X" + s_hex);
return n_num;
}
|
In some cases '#' has to be removed from the beginning of the hex value. I leave this exercise to the reader.
|
|
|
|