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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…