Created
February 26, 2013 07:06
-
-
Save stayradiated/5036557 to your computer and use it in GitHub Desktop.
Create little endians in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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