Skip to content

Instantly share code, notes, and snippets.

@stayradiated
Created February 26, 2013 07:06
Show Gist options
  • Save stayradiated/5036557 to your computer and use it in GitHub Desktop.
Save stayradiated/5036557 to your computer and use it in GitHub Desktop.
Create little endians in JavaScript.
function dec2hex (dec) {
hex = dec.toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return hex;
}
function toLittleEndian (number, dontPad) {
var power = Math.floor((Math.log(number) / Math.LN2) / 8) * 8;
var multiplier = Math.pow(2, power);
var value = Math.floor(number / multiplier);
var remainder = number % multiplier;
var endian = "";
if (remainder > 255) {
endian += toLittleEndian(remainder, true);
} else if (power !== 0) {
endian += this.dec2hex(remainder);
}
endian += this.dec2hex(value);
if (!dontPad) {
var padding = 16 - endian.length;
for (var i = 0; i < padding; i++) {
endian += "0";
}
}
return endian;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment