Private helper functions ----- Encode a length as it should be encoded.
function lengthArray(len) {
    var arr = [];

    if (len <= 127) {
        // Return a single byte if the value is 127 or less.
        return [ len ];
    } else {
        // Otherwise encode it as a MSB base-256 integer.
        while (len > 0) {
            arr.push(len % 256);
            len = parseInt(len / 256, 10);
        }
        // Add a length byte in front and set the high bit to indicate
        // that this is a longer value than one byte.
        arr.push(128 + arr.length);
        arr.reverse();
        return arr;
    }
}