Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

JavaScript Code for Binary to Hexadecimal - Hexadecimal to Binary Conversion

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

00000
00011
00102
00113
01004
01015
01106
01117
10008
10019
1010A
1011B
1100C
1101D
1110E
1111F

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);

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro



Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2024 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268