convert hex to binary in javascript
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;
}
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
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)
);