Reputation: 1713
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
Upvotes: 26
Views: 68283
Reputation: 1
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
Upvotes: 0
Reputation: 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;
}
Upvotes: -1
Reputation: 1
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');
Upvotes: 0
Reputation: 121
The simplest implementation
const hex2bin = (data) => data.split('').map(i =>
parseInt(i, 16).toString(2).padStart(4, '0')).join('');
Upvotes: 10
Reputation: 129
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
Upvotes: 0
Reputation: 192
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;
}
Upvotes: 0
Reputation: 480
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;
}
Upvotes: 0
Reputation: 794
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;
}
Upvotes: 17
Reputation: 966
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)
}
Upvotes: 2
Reputation: 7136
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.
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
Upvotes: 55
Reputation: 6366
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)
);
Upvotes: 10