How do I implement hex2bin()?

52,317

Solution 1

JavaScript doesn't have support for binary data. Nevertheless you can emulate this with regular strings.

var hex = "375771", // ASCII HEX: 37="7", 57="W", 71="q"
    bytes = [],
    str;

for(var i=0; i< hex.length-1; i+=2){
    bytes.push(parseInt(hex.substr(i, 2), 16));
}

str = String.fromCharCode.apply(String, bytes);

alert(str); // 7Wq

Solution 2

To answer your question:

function Hex2Bin(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(2)}

Here are some further functions you may find useful for working with binary data:

//Useful Functions
function checkBin(n){return/^[01]{1,64}$/.test(n)}
function checkDec(n){return/^[0-9]{1,64}$/.test(n)}
function checkHex(n){return/^[0-9A-Fa-f]{1,64}$/.test(n)}
function pad(s,z){s=""+s;return s.length<z?pad("0"+s,z):s}
function unpad(s){s=""+s;return s.replace(/^0+/,'')}

//Decimal operations
function Dec2Bin(n){if(!checkDec(n)||n<0)return 0;return n.toString(2)}
function Dec2Hex(n){if(!checkDec(n)||n<0)return 0;return n.toString(16)}

//Binary Operations
function Bin2Dec(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(10)}
function Bin2Hex(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(16)}

//Hexadecimal Operations
function Hex2Bin(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(2)}
function Hex2Dec(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(10)}

Solution 3

function hex2bin(hex)
{
    var bytes = [], str;

    for(var i=0; i< hex.length-1; i+=2)
        bytes.push(parseInt(hex.substr(i, 2), 16));

    return String.fromCharCode.apply(String, bytes);    
}

thanks to Andris!


Other useful information about this topic (dex2bin,bin2dec) can be found here. According to that, here is a bin2hex solution:

parseInt(1100,2).toString(16); //--> c

Solution 4

Although not an answer to the actual question, it is perhaps useful in this case to also know how to reverse the process:

function bin2hex (bin)
{

  var i = 0, l = bin.length, chr, hex = ''

  for (i; i < l; ++i)
  {

    chr = bin.charCodeAt(i).toString(16)

    hex += chr.length < 2 ? '0' + chr : chr

  }

  return hex

}

As an example, using hex2bin on b637eb9146e84cb79f6d981ac9463de1 returns ¶7ëFèL·mÉF=á, and then passing this to bin2hex returns b637eb9146e84cb79f6d981ac9463de1.

It might also be useful to prototype these functions to the String object:

String.prototype.hex2bin = function ()
{

  var i = 0, l = this.length - 1, bytes = []

  for (i; i < l; i += 2)
  {
    bytes.push(parseInt(this.substr(i, 2), 16))
  }

  return String.fromCharCode.apply(String, bytes)   

}

String.prototype.bin2hex = function ()
{

  var i = 0, l = this.length, chr, hex = ''

  for (i; i < l; ++i)
  {

    chr = this.charCodeAt(i).toString(16)

    hex += chr.length < 2 ? '0' + chr : chr

  }

  return hex

}

alert('b637eb9146e84cb79f6d981ac9463de1'.hex2bin().bin2hex())

Solution 5

All proposed solutions use String.fromCharCode, why not simply using unescape?

String.prototype.hex2bin = function()
{ 
   var i = 0, len = this.length, result = "";

   //Converting the hex string into an escaped string, so if the hex string is "a2b320", it will become "%a2%b3%20"
   for(; i < len; i+=2)
      result += '%' + this.substr(i, 2);      

   return unescape(result);
}

and then:

alert( "68656c6c6f".hex2bin() ); //shows "hello"
Share:
52,317

Related videos on Youtube

MartyIX
Author by

MartyIX

Updated on July 09, 2022

Comments

  • MartyIX
    MartyIX almost 2 years

    I need to communicate between Javascript and PHP (I use jQuery for AJAX), but the output of the PHP script may contain binary data. That's why I use bin2hex() and json_encode() on PHP side.

    How do I convert the hexadecimal string in binary string, with JavaScript?

  • Michael
    Michael over 10 years
    bin2hex seems really inefficient (and slow) if I want to, say, convert a large image file into a hex string...
  • yckart
    yckart almost 8 years
    why not simply using unescape - Just because it's deprecated. ;)
  • Alan Mroczek
    Alan Mroczek over 7 years
    you can use decodeURIComponent instead of unescape and this is perfectly fine. However thanks @Marco, I used your solution
  • Michael
    Michael about 7 years
    This doesn't seem to be working with actual binary data, rather with ASCII representations of binary data.
  • Green
    Green almost 7 years
    Your functions are wrong. At least Hex2Bin and Bin2Hex. Didn't even try other afterI got wrong results with those two. Try yourself Hex2Bin => Bin2Hex
  • huggie
    huggie almost 7 years
    I've been using this set for a long time. And I am beginning to use Hex2Bin and realized it just now. Hex2Bin is broken. I think Bin2Hex is also wrong.
  • huggie
    huggie almost 7 years
    For the two functions, here is one that works: stackoverflow.com/questions/17204912/…
  • Phil
    Phil about 6 years
    It depends if you mean 1 bit binary representation (0/1) or 8 bit binary representation (bytes of data). In this answer "bin" means base 2 (binary 1s and 0s)
  • Steve Owens
    Steve Owens about 6 years
    Your Hex2Bin function doesn't work for anything longer than a single pair of hex values.
  • hanshenrik
    hanshenrik over 5 years
    when this answer was written, it was probably correct, but JS does support binary data now, with the Uint8Array :) it's very cubersome to use compared to php's binary strings which essentially are Uint8Array's already, but it's better than nothing ¯\_(ツ)_/¯
  • Phil
    Phil over 4 years
    Uncaught ReferenceError: Buffer is not defined