Skip to content

Instantly share code, notes, and snippets.

@adoc
Created January 25, 2014 05:39
Show Gist options
  • Save adoc/8612321 to your computer and use it in GitHub Desktop.
Save adoc/8612321 to your computer and use it in GitHub Desktop.
bytes.js: Just some functions to help out with byteArrays.
/*
Just some functions to help out with byteArrays.
Authors and Inspiration: github.com/adoc and Various Others.
*/
// Converts an integer to bytes.
var intToBytes = function(n) {
var result = '';
while (n) {
result = String.fromCharCode(n & 0xFF) + result;
n >>= 8;
}
return result;
}
// Converts bytes to an integer.
var bytesToInt = function(b) {
var n = 0;
var blen = b.length;
for(i=0; i<blen; i++) {
n += b[blen-i-1].charCodeAt() << 8 * i;
}
return n;
}
// http://stackoverflow.com/a/11893415
function wordsToBytes(wordArray) {
var byteArray = [], word, i, j;
for (i = 0; i < wordArray.length; ++i) {
word = wordArray[i];
for (j=3; j >= 0; --j) {
byteArray.push((word >> 8 * j) & 0xFF);
}
}
return byteArray;
}
// Array of bytes to a WordArray.
function bytesToWords(byteArray) {
var wordArray = [];
for (var i=0; i<Math.ceil(byteArray.length/4); i++) {
wordArray[i] = 0;
}
for (var i=0; i<byteArray.length; i++) {
var wi = (i - (i % 4)) / 4;
var j = 3 - i % 4;
wordArray[wi] += byteArray[i] << 8 * j;
}
return wordArray;
}
// byteArray to String. Also appends to `outString`.
function bytesToString(byteArray, outString) {
outString = outString || '';
for (var i=0; i<byteArray.length; i++) {
outString += String.fromCharCode(byteArray[i]);
}
return outString;
}
// String to byteArray. Also appends to `byteArray`.
function stringToBytes(string, byteArray) {
byteArray = byteArray || [];
for (var i=0; i<string.length; i++) {
byteArray.push(string[i].charCodeAt());
}
return byteArray;
}
// Strips trailing 0 bytes.
function stripArray(byteArray) {
for (var i=byteArray.length; i>0; i--) {
if (byteArray[i-1] == 0) {
byteArray.splice(i-1, 1);
} else {
return byteArray;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment