Skip to content

Instantly share code, notes, and snippets.

@pearlchen
Last active December 27, 2015 01:19
Show Gist options
  • Save pearlchen/7244453 to your computer and use it in GitHub Desktop.
Save pearlchen/7244453 to your computer and use it in GitHub Desktop.
<script>
/** Convert a decimal number to a hex number. */
function convertDecToHex(dec) {
var BASE = 16,
result = '';
return getHex( dec );
function getHex(num){
var whole = Math.floor( num / BASE ),
remainder = num % BASE,
tempHex = getHexLetter(remainder);
//console.log( whole + " r " + remainder + " // " + tempHex );
// add the hex letter to the BEGINNING of the previous hex string
result = tempHex + result;
if ( whole > 0 ) {
return getHex( whole ); //recurse until divisible whole is 0
}else{
return result;
}
}
function getHexLetter(num){
if ( num <= 9 ) return num;
var letters = ["A", "B", "C", "D", "E", "F"];
var i = num - 10;
return letters[i];
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment