Hex to Decimal and Decimal to Hex

Computers work with binary numbers (base 2) while people usually work with decimal (base 10). Binary numbers are long strings of ones and zeros that are difficult for people to read and so to make it easier for people to read the numbers the computers are working with a different number base that is directly related to the binary number is generally used. Originally octal (base 8) where three binary digits are combined to display as a value between 0 and 7 was used however as computer bytes standardised on a length of eight binary digits (or bits) hexadecimal (base 16) using A through F to represent the values 10 through 15 as a single digit has become the alternative of choice as it easily allows the content of a byte to be displayed as a two digit hexadecimal number between 00 and FF.

As an example, colours used on a web page have one byte allocated for each of the red, green, and blue components with each being able to therefore have any value between 00000000 and 11111111 (binary) or 00 and FF (hexadecimal) or 0 and 255 (decimal). We can specify the colour white in a stylesheet as either '#FFFFFF' using hexadecimal or rgb(255,255,255) using decimal.

Not everything allows both alternatives for handling numbers and paradoxically in order to be able to perform calculations in JavaScript using hexadecimal numbers we need to first convert them to decimal so that the computer can then convert them to binary. Being able to easily convert between decimal and hexadecimal and back is necessary whenever we need to work with hexadecimal numbers.

JavaScript actually provides very simple ways to do these conversions but the names that they use are not obvious and are therefore not easily remembered. To get around this the solution is to set up our own functions with more obvious names that call the code to do the conversions for us.

d2h = function(d) {return d.toString(16);}
h2d = function(h) {return parseInt(h,16);}
dec = h2d(hex); // set dec to the decimal equivalent of the hexadecimal value in hex
hex = d2h(dec); // set hex to the hexadecimal equivalent of the decimal number in dec


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow