0

I've got a 256 character long string I'm using as bit field that I want to shrink with JavaScript so I can use it as part of a query string in a url. I'm not sure what the best/most efficient way to do this is.

I think I want something similar to this solution, Create a large bitfield, but my bit field has only 1s and 0s.

Any ideas?

Community
  • 1
  • 1
Stuart Memo
  • 1,138
  • 4
  • 14
  • 30
  • Have you considered Base64 encode? In the link you posted they're using base-36. – Halcyon Aug 30 '13 at 09:27
  • @FritsvanCampen That will make it longer, not shorter! – Barmar Aug 30 '13 at 09:27
  • @Barmar not if his input is bits rather than characters. One base-64 character represents 6 bits. So you'll get a 43 character string. – Halcyon Aug 30 '13 at 09:28
  • Just by converting it to hex you'll shrink it to 64 chars, grouping bits by byte and converting to base64 will shrink it even more ... – yent Aug 30 '13 at 09:30
  • To clarify, what @Barmar means is that when you base64-encode a string, where characters are 8 bits (1 byte), into a 6 bit encoding, your string will grow by ~33%. But your input is bits, not characters. – Halcyon Aug 30 '13 at 09:32
  • What do you mean by `256 character long bit field`? Do you mean 256*8 bits? Or a string like `101110001110101...` that's 256 characters long? – Barmar Aug 30 '13 at 09:34
  • Sorry, it's a string that's 256 characters long. – Stuart Memo Aug 30 '13 at 09:35
  • Which I'm guessing I'd parseInt to make it a number first? After splitting it that is to avoid JavaScript's troubles with large numbers. – Stuart Memo Aug 30 '13 at 10:55

1 Answers1

0

So here's what I came up with. My bit fields are held in an array. If I split the array into smaller chunks of 16, I can do the following.

var bitArray = [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];

console.log('Original array', bitArray);
// Logs "Original array [ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]"

var stringToArray = function (str) {
    var arr = [];

    for (var i = 0; i < str.length; i++) {
        arr.push(parseInt(str[i], 10));
    }

    return arr;
}; 

var addPadding = function (str, maxLength) {

    for (var i = 0; i < maxLength - str.length; i++) {
        str = '0' + str;
    }

    return str;
};

var shrink = function (str) {
    str = parseInt(str, 10);
    str = str.toString(36);
    return str;
};

var expand = function (str) {
    str = parseInt(str, 36) + '';
    return str;
};

var qs = bitArray.join('');

qs = shrink(qs);

console.log('Shrunk value', qs);
// Logs "Shrunk value 3xsdgob0n"

// 10 characters is the maximum length of base36 string when converted.
qs = addPadding(qs, 10);
qs = addPadding(expand(qs), bitArray.length);

console.log('Re-expanded array', stringToArray(qs));
// Logs "Re-expanded array [ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]"
Stuart Memo
  • 1,138
  • 4
  • 14
  • 30