// toHex converts from decimal to Hex // Analysis function toHex(number) { var temp=0; var hexNumber = ""; var hexString = "0123456789ABCDEF"; hexNumber += hexString.charAt(Math.floor(number/16)); hexNumber += hexString.charAt(Math.floor(number%16)); return hexNumber; }
To make the conversion from decimal to hex, the function first divides 'number' by 16. This is necessary to find the first digit in the hex number. For example, the hexadecimal representation of the number 237 is 0xED (the 0x specifies that a number is a hexadecimal number). 237 divided by 16 is 14.8125.
All that we are interested in here is the whole number portion of the answer, so the Math.floor() method is used to round down to the next integer less than or equal to the current value (14). Looking at the hexString, the character 'E' is in position 14.
The next step is to take number modulus 16 (number%16). Remember that the modulus operator
(%) returns the whole number remainder from a division operation. For example, 237 % 16 is 13 (14
times 16 equals 224. 237 minus 224 equals 13). In hexString, the 13th character is E, which is added to
the hexNumber variable.