Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...