As part of a project I have a string of numbers between 0 and 3, for example:
2030000000000000000030000000000000000003333212111221121301
I want to pass this string through an URL, so I figured I could try using a bitfield since each number only uses a maximum of 2 bits each. I wrote the following functions in my class to convert such a string to and from an array of integers used as bitfields for the data:
makeBuildBitfield: function(build) {
var b = build.split('');
var f = [3, 0]; // the "3" is there for future purposes
var i = 1;
var j = 0;
for (var t in b) {
if (j < 14) {
f[i] |= b[t];
f[i] = f[i] << 2;
++j;
} else {
f[i] |= b[t];
++i;
f[i] = 0;
j = 0;
}
}
return f.join('.');
},
getBuildFromBitfield: function(bitfield) {
b = bitfield.split('.');
var ba = [];
for (var x = 1; x < b.length; ++x) { //start from 1 to skip the "3"
ba[x] = [];
var n = b[x];
for (var y = 14; y >= 0; --y) {
ba[x][y] = n & 3;
n = n >>> 2;
}
}
build = '';
for (var a in ba) build += ba[a].join('');
return build;
},
They do seem to be working, but... not quite. When i pass the string from my example at the start:
2030000000000000000030000000000000000003333212111221121301
I get the following output:
3.587202560.786432.4089.156916164
However, when I pass this to the function that is supposed to convert it back, it gives me this:
203000000000000000003000000000000000000333321021112211213010
Note the extra zeros in the second string. Now, I'm new to operating on bits and this is my first attempt at it, but I've searched around and read the articles I could find on the subject, and I've tried to write down on a sheet of paper the state of the bits as the loop progresses to try and understand what is going on, but I just can't seem to figure out why it goes wrong and what those extra zeros are doing there. Either my string->bitfield
function is off, or the other one, or quite possibly both. But I really can't figure it out, so does anyone have any suggestions as to how I could fix whatever it is that's going wrong?
Thanks in advance!