Skip to content
Advertisement

convert hex to binary in javascript

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement