Javascript Convert Decimal to Hex
Javascript code to convert decimal to hex code requires a typical logic for generating the hexadecimal output. In hexadecimal numeric system numbers range start from 0 to 9 and then A, B, C, D, E, F. Hex code consists of total 16 indexes starting from 0 to 9 and further it represents 10 with A and so on 15 with F. To convert decimal to hex in javascript code first you need a function that can be called in a loop to convert the decimal number into hex code.
Example
// function to generate the hex code
function getHex(dec) {
var hexArray = new Array("0", "1", "2", "3",
"4", "5", "6", "7",
"8", "9", "A", "B",
"C", "D", "E", "F");
var code1 = Math.floor(dec / 16);
var code2 = dec - code1 * 16;
var decToHex = hexArray[code2];
return (decToHex);
}
Above javascript function returns the hex code equivalent for the last digit of the decimal number. This function can be called repeatedly to get the hex code of remaining leading digits of the decimal number.
Following javascript function calls the above function each time to get the hex code for a decimal number. It sends the value to getHex function and retrieves the hex code of last digit. Then evaluates the remaining part using Math.floor(dec / 16). This value is sent to the while loop to pass the condition whether the remaining evaluated decimal value is greater than 15 or not. If remaining value in greater than 15 then it passes the test and enters the while loop. This process continues until the remaining decimal value becomes less than 15.
function toHexCode(dec) {
// array to store the hex code for each value passed
// to the getHex function
var hexCode = new Array();
// variable to define the dynamic array index
// for hexCode array
var i = 0;
// while loop to run until dec variable
// is greater than 15
while (dec > 15) {
hexCode[i] = getHex(dec);
// evaluate dec each time to
// pass the while loop condition
dec = Math.floor(dec / 16);
i += 1;
}
// store the last value
// skiped due to loop condition
// for dec < 15
hexCode[i] = getHex(dec);
// variable to store the hex Codes
var decToHex = "";
// reverse loop on hexCode to
// generate the right order of hex codes
for (i = hexCode.length - 1; i >= 0; i--) {
decToHex += hexCode[i];
}
return decToHex;
}
Use the above JavaScript functions to convert decimal to hex and try the following code to run the script:
<input id="Text1" type="text" /><br />
<input id="Text2" type="text" />
<input id="Button1"
type="button"
value="get hex code"
onclick="document.getElementById('Text2').value = toHexCode(document.getElementById('Text1').value);" />
Continue to next tutorial: Javascript Convert RGB to Hex to learn how to convert RGB color code to its equivalent hexadecimal color code value.

dec.toString(16);