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.


Need Your Help

Blocking input from keyboard HID

c# wpf barcode-scanner hid

I am in the process of integrating support for USB barcode scanners into a WPF application, but I have hit a snag.

ReportService2005 FindItems by parameter with boolean data type

c# sql-server reporting-services

I've added a boolean parameter called IsNewReport to some of my reports and I'm trying get a list of these reports using the SSRS web service (ReportService2005.asmx).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.