// toDec assumes the Hex number is between 0 & 255
// Analysis

function toDec(number)
{

var hexString = "0123456789ABCDEF";
var dec = 0;

dec = hexString.indexOf(number.charAt(0)) * 16 + hexString.indexOf(number.charAt(1));

return dec;
}

The purpose of this function is to convert from a hexadecimal (base 16) number to a decimal (base 10) number. To accomplish this, the code creates a string containing all of the hexadecimal values (hexString), and uses the indexOf() method to find the position of the character in the string.

This is the first time the indexOf() method has been introduced. The indexOf() method searches for the first occurrence of one string (the first argument sent to it) in the current string. The indexOf() method also has an optional second argument that allows you to specify where in the target string to begin your search. For example, the phrase

"How now brown cow?".indexOf("ow")

would return 1. The phrase

"How now brown cow?".indexOf("ow", 6)

would return 10.

Because the position of each character in the string corresponds to its value, the indexOf() method converts a single hexidecimal digit to its decimal value.

To covert the two digit hexadecimal number to its corresponding decimal value, the first character is extracted using the charAt() method with the argument of 0. This value is multiplied by 16, and then added to the decimal value of the second character.

Close Window