JavaScript Code for Binary to Hexadecimal - Hexadecimal to Binary Conversion
By Stephen Bucaro
To be honest, you don't really need JavaScript to convert a binary number to a
hexadecimal number. You simply go from right to left breaking the binary number into
groups of four bits, and then use a binary to hexadecimal lookup table to replace
each group with its respective hexadecimal digit.
Binary to Hexadecimal Table
0000 | 0 |
0001 | 1 |
0010 | 2 |
0011 | 3 |
0100 | 4 |
0101 | 5 |
0110 | 6 |
0111 | 7 |
1000 | 8 |
1001 | 9 |
1010 | A |
1011 | B |
1100 | C |
1101 | D |
1110 | E |
1111 | F |
However, if you must use JavaScript, say to create a web application, the code
to convert a binary number to hexadecimal number is shown below.
<script>
var inBin = "111001100101";
var len = inBin.length;
// determine how many bits in first nibble
var firstBits = len % 4;
// if firstBits > 0 generate padding to make even nibbles
// increase len by number of padding bits
var inPadded = "";
if(firstBits > 0)
{
var padding = "";
for(var i = 0; i < 4 - firstBits; i++)
{
padding = "0" + padding;
len++;
}
inPadded = padding + inBin;
}
else
{
inPadded = inBin;
}
// Binary to hexadecimal lookup table in
// a multidimensional array
var hexDigits = [
["0000","0"],
["0001","1"],
["0010","2"],
["0011","3"],
["0100","4"],
["0101","5"],
["0110","6"],
["0111","7"],
["1000","8"],
["1001","9"],
["1010","A"],
["1011","B"],
["1100","C"],
["1101","D"],
["1110","E"],
["1111","F"]];
// grab the input bits nibble by nibble
// look up in array and fetch hexadecimal value
var nibble = "";
var outHex = "";
for(var start = 0; start <= len - 4; start += 4)
{
nibble = inPadded.substring(start, start + 4);
for(var j = 0; j < hexDigits.length; j++)
{
if(nibble == hexDigits[j][0])
{
outHex += hexDigits[j][1];
}
}
}
alert(outHex);
|