Created
September 24, 2015 09:18
-
-
Save Androguide/4d003fdba4266e46f305 to your computer and use it in GitHub Desktop.
Converts decimal to binary and outputs a table of the powers of 2 for manual conversion
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 () { | |
"use strict"; | |
window.BinaryTranslate = function (number) { | |
var binaryTable = [[], []]; | |
var master = number; | |
var neighbour = nearestPowerOf2(number); | |
for (var i = neighbour; i >= 0; i--) { | |
binaryTable[0].push(Math.pow(2, i)); | |
binaryTable[1].push(master - Math.pow(2, i) >= 0 ? 1 : 0); | |
if (master - Math.pow(2, i) >= 0) | |
master = master - Math.pow(2, i); | |
} | |
console.log('Result: ' + decimalToBinary(number)); | |
console.table(binaryTable); | |
}; | |
function nearestPowerOf2(number) { | |
return Math.ceil(Math.log2(number)); | |
} | |
function decimalToBinary(number) { | |
return (number >>> 0).toString(2); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment