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


i'm writing bitstream implementation in pure javascript. i'm representing bits strings of "0" , "1"s - figured more efficient arrays of 0 , 1 , don't want use uint32 - , need convert strings , representation. here's got far:

function uinttobitstring(uint, bit_length) {     var res = uint.tostring(2);     if (res.length > bit_length) {         throw new error("the number " + uint + " big 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 = [];     (var i=0; < val.length; i++) {         bit_pieces[i] = uinttobitstring(val.charcodeat(i), 8);     }     return bit_pieces.join(""); }  function binreptostring(bits) {     var charcodes = [];     (var i=0; < bits.length; += 8) {         charcodes[i / 8] = parseint(bits.slice(i, i+8), 2);     }     return string.fromcharcode.apply(string, charcodes); } 

although i'm familiar javascript i'm not versed in makes faster code vs. slower code. there more efficient way above using pure javascript?

an obvious improvement in uinttobitstring like

function uinttobitstring(uint, bit_length) {     var max = 1 << bit_length;     if(uint >= max)         throw new error("the number " + uint + " big fit in " +                          bit_length + " bits");     return (uint | max).tostring(2).substring(1); } 

as 2 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 matters, should use ints bit manipulations , not 1/0 strings.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -