22

I need to convert hex into binary using javascript.

example: 21 23 00 6A D0 0F 69 4C E1 20

should result in: ‭0010000100100011000000000110101011010000000011110110100101001100‬

Does anyone know of a javascript library I might use to accomplish this?

Harriet

Harriet
  • 1,633
  • 5
  • 22
  • 36

9 Answers9

49

You can create a function converting a hex number to binary with something like this :

function hex2bin(hex){
    return ("00000000" + (parseInt(hex, 16)).toString(2)).substr(-8);
}

For formatting you just fill a string with 8 0, and you concatenate your number. Then, for converting, what you do is basicaly getting a string or number, use the parseInt function with the input number value and its base (base 16 for hex here), then you print it to base 2 with the toString function. And finally, you extract the last 8 characters to get your formatted string.


2018 Edit :

As this answer is still being read, I wanted to provide another syntax for the function's body, using the ES8 (ECMAScript 2017) String.padStart() method :

function hex2bin(hex){
    return (parseInt(hex, 16).toString(2)).padStart(8, '0');
}

Using padStart will fill the string until its lengths matches the first parameter, and the second parameter is the filler character (blank space by default).

End of edit


To use this on a full string like yours, use a simple forEach :

var result = ""
"21 23 00 6A D0 0F 69 4C E1 20".split(" ").forEach(str => {
  result += hex2bin(str)
})
console.log(result)

The output will be :

00100001001000110000000001101010110100000000111101101001010011001110000100100000

Seblor
  • 6,947
  • 1
  • 25
  • 46
  • Why first approach does not work for this hex: `F9C6400001000000000000000000000000000000000000000000000000000000000000011100000000000000000000000000000000`? – POV Oct 06 '19 at 18:08
  • 1
    @OPV That is because the first version uses a substring function, limiting the output to 8 digits, since I did not expect the input to be more than a byte, and wanted to output exactly one byte, including the leading 0s. The second version, using `padStart`, outputs *at least* one "full" byte. – Seblor Oct 07 '19 at 07:13
13

Unfortunately, previous answers seem not to be working with very large values (e.g., 512 bits so common in cryptography). This solution may be a bit slower, but it guarantees dealing with input of any length.

function hex2bin(hex){
    hex = hex.replace("0x", "").toLowerCase();
    var out = "";
    for(var c of hex) {
        switch(c) {
            case '0': out += "0000"; break;
            case '1': out += "0001"; break;
            case '2': out += "0010"; break;
            case '3': out += "0011"; break;
            case '4': out += "0100"; break;
            case '5': out += "0101"; break;
            case '6': out += "0110"; break;
            case '7': out += "0111"; break;
            case '8': out += "1000"; break;
            case '9': out += "1001"; break;
            case 'a': out += "1010"; break;
            case 'b': out += "1011"; break;
            case 'c': out += "1100"; break;
            case 'd': out += "1101"; break;
            case 'e': out += "1110"; break;
            case 'f': out += "1111"; break;
            default: return "";
        }
    }

    return out;
}
Nick Ivanov
  • 754
  • 7
  • 7
10

You can use parseInt and toString to change the radix of a number.

function convertNumber(n, fromBase, toBase) {
  if (fromBase === void 0) {
    fromBase = 10;
  }
  if (toBase === void 0) {
    toBase = 10;
  }
  return parseInt(n.toString(), fromBase).toString(toBase);
}
console.log(
  convertNumber("f", 16, 10),
  convertNumber("f", 16, 2),
  convertNumber("1111", 2, 10),
  convertNumber("1111", 2, 16)
);
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
8

The simplest implementation

const hex2bin = (data) => data.split('').map(i => 
parseInt(i, 16).toString(2).padStart(4, '0')).join('');
SKONIKS
  • 81
  • 1
  • 4
2

This work for me.

function hex2bin(hexSource) {
    var bin = '';
    for (var i=0;i<hexSource.length;i=i+2) {
        bin += String.fromCharCode(hexdec(hexSource.substr(i,2)));
    }
    return bin;
}

function hexdec(hexString) {
    hexString = (hexString + '').replace(/[^a-f0-9]/gi, '')
    return parseInt(hexString, 16)
}
Nyi Nyi
  • 916
  • 7
  • 13
0

this might be faster method, concept is considering integer's capacity we can divide hex string into blocks of 8 chars instead of 1 char:

function hexToBinary(hex) {
    var binary = "";
    var remainingSize = hex.length;
    for (var p = 0; p < hex.length/8; p++) {
        //In case remaining hex length (or initial) is not multiple of 8
        var blockSize = remainingSize < 8 ? remainingSize  : 8;

        binary += parseInt(hex.substr(p * 8, blockSize), 16).toString(2).padStart(blockSize*4,"0");

        remainingSize -= blockSize;
    }
    return binary;
}
Alireza Rinan
  • 480
  • 6
  • 9
  • It's faster compared to other parseInt/toString/padStart methods. But it's slower than using a lookup table for each character (which you could then speed up further with a 2-char lookup table, 3-char lookup table, etc.) For very large hex strings, you could generate the lookup table as a one-time cost. At some point there are diminishing returns on a larger lookup table. Fun stuff to play with. – spex Dec 19 '21 at 16:31
0

I agree for hex to binary going character by character isn't the fastest or most efficient, but I think it's difficult to do that and still have readable code. I think these two are good starting points for those less familiar.

function hex2bin(hex) {
  let bin = "";
  let bitsInHex = 4;

  Array.from(hex).forEach(
    function (char) {
      let currentBin = parseInt(char, 16).toString(2);

      if (currentBin.length < bitsInHex) {
        let padding = "0".repeat(bitsInHex-currentBin.length);
        currentBin = padding + currentBin;
      }

      bin += currentBin;
    }
  );

  return bin;
}

function bin2hex(bin) {
  let hex = "";
  let bitsInHex = 4;

  for (let i = 0; i < bin.length; i = i + bitsInHex) {
    let eightBits = bin.substr(i, bitsInHex);
    let currentHex = (parseInt(eightBits, 2)).toString(16).toUpperCase();
    hex += currentHex;
  }

  return hex;
}
Blake Gearin
  • 175
  • 1
  • 10
0

For some reason, Javascript gives only 0000 if the character length is greater than 12. I am self-taught JS, so don't know the reason.

But I have a workaround for this problem. Just divided the original string into an array of smaller chunks, and then find their binary value.

function hex2bin(hex) {
    let chunks = hex.match(/.{1,8}/g), bin = ''
    chunks.forEach(c => (bin += parseInt(c, 16).toString(2)))
    bin = bin.padStart(4, '0')
    return bin
}

I think this would be much easier to implement than to use individual binary values of hex as mentioned in this solution.
My solution is somewhat similar to this

GrayGalaxy
  • 91
  • 7
0

I found a library what does this easier.

https://gist.github.com/faisalman/4213592

to convert hex to binary type ConvertBase.hex2bin('your hex number');

nullty32
  • 1
  • 2
  • 1
    There are already lots of vanilla JS examples up for grabs in this old question. Maybe there is no need to point to a third party library. – Marc Sances Dec 20 '22 at 10:20