Skip to content

Instantly share code, notes, and snippets.

@pixeldrew
Last active December 15, 2015 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixeldrew/5311519 to your computer and use it in GitHub Desktop.
Save pixeldrew/5311519 to your computer and use it in GitHub Desktop.
Converts a decimal array to a binary array, eg [12,13,5,4] == [0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] f2 is almost 6x faster in v8.
var f1 = function (a) {
return a.map(function (n) {
// convert number to decimal reverse the order then left pad it to a byte
return String((n).toString(2).split('').reverse().join('') + Array(8 + 1).join("0")).substr(0, 8);
}).join('')
.split('')
.map(function (n) {
return +n; // convert each of the numbers to int
});
};
var f2 = function (bitRow) {
var calcArray = new Array(bitRow.length * 8),
pos = 0,
len = bitRow.length;
for (var i = 0; i < len; i++, pos++) {
var currentByte = bitRow[i];
calcArray[pos] = (currentByte & 1);
pos++;
calcArray[pos] = (currentByte & 2) >> 1;
pos++;
calcArray[pos] = (currentByte & 4) >> 2;
pos++;
calcArray[pos] = (currentByte & 8) >> 3;
pos++;
calcArray[pos] = (currentByte & 16) >> 4;
pos++;
calcArray[pos] = (currentByte & 32) >> 5;
pos++;
calcArray[pos] = (currentByte & 64) >> 6;
pos++;
calcArray[pos] = (currentByte & 128) >> 7;
}
return calcArray;
};
console.time('Time f1');
for(var i=0;i<1000;i++) {
f1([17, 160, 83, 41, 25]);
}
console.timeEnd('Time f1');
console.time('Time f2');
for(var i=0;i<1000;i++) {
f2([17, 160, 83, 41, 25]);
}
console.timeEnd('Time f2');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment