Category Archives: javascript

Base64 decoding in Javascript

I never wrote a decoder in my previous post, so here’s my first iteration while half asleep.

function b64d(str) {

        var charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";


        var str_pos = 0;
        var str_len = str.length;

        var numbits=0;
        var curval=0;

        var data = "";
        var done = false;

        while (done == false){
                // Not enough bits, get more
                if (numbits < 8) {
                        var nextchar = str.charAt(str_pos++);
                        if (nextchar == "=") { break; }
                        var sixbits = charset.indexOf(nextchar);
                        curval = (curval << 6) | sixbits;
                        numbits += 6;
                } else {

                        nextbyte = curval >> (numbits - 8);
                        curval = curval - (nextbyte << numbits - 8);
                        numbits -= 8;

                        data += String.fromCharCode(nextbyte);

                        if (str_pos >= str_len && numbits < 8){
                                done = true;
                        }
                }
        }

        return data;

}

Base64 in Javascript

Decided to play around with writing my own base64 in javascript, as a piece to a larger project I’m considering playing around with.

function b64e(str) {

        var charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

        var str_pos = 0;
        var str_len = str.length;

        var numbits=0;
        var curval=0;

        var b64str = "";
        var done = false;

        while (done == false){
                // Not enough bits, get more
                if (numbits < 6) {
                        var nextbyte = str.charCodeAt(str_pos++);
                        curval = (curval << 8) | nextbyte;
                        numbits += 8;
                }

                sixbits = curval >> (numbits - 6);
                curval = curval - (sixbits << numbits - 6);
                numbits -= 6;

                b64str += charset[sixbits];

                if (str_pos >= str_len && numbits < 6){
                        done = true; 
                }
        }

        //handle extra bits now
        if (numbits > 0){
                sixbits = curval << (6-numbits)
                numbits -= 6;
                b64str += charset[sixbits];
        }

        b64str += Array((numbits/-2) + 1).join('=');

        return b64str;

}