# Efficient way to convert from string to 0s and 1s, and 0s and 1s to string?

I'm writing a bitstream implementation in pure JavaScript. I'm currently representing bits as strings of "0" and "1"s - figured this would be more efficient than arrays of 0 and 1 and I don't want to use Uint32 - and I need to convert strings to and from this representation. Here's what I got so far:

function uintToBitString(uint, bit_length) { var res = uint.toString(2); if (res.length > bit_length) { throw new Error("The number " + uint + " is too big to fit in " + bit_length + " bits"); } if (res.length < bit_length) { res = Array(bit_length - res.length + 1).join("0") + res; } return res; } function stringToBinRep(val) { var bit_pieces = []; for (var i=0; i < val.length; i++) { bit_pieces[i] = uintToBitString(val.charCodeAt(i), 8); } return bit_pieces.join(""); } function binRepToString(bits) { var charCodes = []; for (var i=0; i < bits.length; i += 8) { charCodes[i / 8] = parseInt(bits.slice(i, i+8), 2); } return String.fromCharCode.apply(String, charCodes); }

Although I'm familiar with JavaScript I'm not very well versed in what makes faster code vs. slower code. Is there a more efficient way to do the above using only pure JavaScript?

## Answers

An obvious improvement in uintToBitString would be like

function uintToBitString(uint, bit_length) { var max = 1 << bit_length; if(uint >= max) throw new Error("The number " + uint + " is too big to fit in " + bit_length + " bits"); return (uint | max).toString(2).substring(1); }

As for the two others, I'd rather use String.replace there:

function stringToBinRep(val) { return val.replace(/./g, function($0) { return uintToBitString($0.charCodeAt(0), 8) }) } function binRepToString(bits) { return bits.replace(/.{8}/g, function($0) { return String.fromCharCode(parseInt($0, 2)) }) }

That said, if performance really matters, you should use ints for bit manipulations and not 1/0 strings.