27

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

5
  • 3
    We do not recommend libraries here! If you're interested in an algorithm to do that, you may be in the right place. Otherwise, no. Commented Jul 12, 2017 at 9:24
  • Possible duplicate of stackoverflow.com/questions/7695450/… Commented Jul 12, 2017 at 9:25
  • 1
    Are you sure about your binary result ? Commented Jul 12, 2017 at 9:33
  • @Seblor, I actually input the hex string into my desktop calculator and hit binary for the above conversion. Commented Jul 12, 2017 at 9:35
  • @Harriet you are missing 16 digits at the end (right side) Commented Jul 12, 2017 at 9:36

11 Answers 11

56

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

Sign up to request clarification or add additional context in comments.

2 Comments

Why first approach does not work for this hex: F9C6400001000000000000000000000000000000000000000000000000000000000000011100000000000000000000000000000000?
@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.
18

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

Comments

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

Comments

10

The simplest implementation

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

Comments

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

Comments

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

1 Comment

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.
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;
}

Comments

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

Comments

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

1 Comment

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.
0

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

something that came to my mind that might be faster but more memory consuming was to create a global json object and add those values to your string something in the lines of the following code thanks to nick for the inspiration

Comments

-1

Generic solution function:

function hexToBinary(hex) 
{
    if (!!!hex)
        throw new Error("hex is undefined or empty!")
    if (hex.length % 2 !== 0)
        throw new Error("Invalid hex value!")

    let bin = ""
    for (let i = 0; i < hex.length; i += 2)
            bin += parseInt(hex.substring(i, i + 2), 16).toString(2)

    return bin;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.