Click to See Complete Forum and Search --> : Hex & Decimal
Dumbass
09-29-2003, 06:58 PM
Just say I have two variables: iHex (number in hexidecimal format - Probably 2 digits), and iDec (number in decimal).
How would I go about converting iHex to a decimal number, and iDec to a hexidecimal?
It can be done by converting between numbers and string, using toString (http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/number.html#1193464) and parseInt (http://devedge.netscape.com/library/manuals/2000/javascript/1.3/reference/toplev.html#1064173), by passing a radix (or base) to the functions. Take a look at the following example:
<script type="text/javascript">
function convert() {
hex = document.vals.hex.value;
int = document.vals.integer.value;
intval = parseInt(hex, 16);
hexval = Number(int).toString(16);
if (hex != "") {
alert ("The integer equivilant of "+hex+" is: "+intval);
}
if (int != "") {
alert ("The hexidecimal value equivilant of "+int+" is: "+hexval);
}
}
</script>
</head>
<body>
<form name="vals" action="">
<p>hexidecimal: <input type="text" name="hex">
integer: <input type="text" name="integer">
<input type="button" value="Convert" onclick="convert();"></p>
</form>