Lets say I have a string in JavaScript with binary data in it. It may look like this:
var binary = \'00001000010001000101010100001110\';
I
Why not using Array.prototype.reduce?
var binstr = "00001000010001000101010100001110"
function bin2hex(b) {
return b.match(/.{4}/g).reduce(function(acc, i) {
return acc + parseInt(i, 2).toString(16);
}, '')
}
function hex2bin(h) {
return h.split('').reduce(function(acc, i) {
return acc + ('000' + parseInt(i, 16).toString(2)).substr(-4, 4);
}, '')
}
console.log(binstr);
> 00001000010001000101010100001110
console.log(bin2hex(binstr));
> 0844550e
console.log(hex2bin(bin2hex(binstr)));
> 00001000010001000101010100001110
Link to jsfiddle here.
Notes:
bin2hex, if you want to convert also trailing chunks of less than 4 bits to hex, replace {4} with {1,4}. However, converting back the result to binary, will produce a string that differs from the original. For example, converting forth and back "111101" would produce "11110001".hex2bin, binary values are left-padded with zeroes so as to have 4 binary digits for every hex digit.