Skip to content

Instantly share code, notes, and snippets.

@Androguide
Created September 24, 2015 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Androguide/4d003fdba4266e46f305 to your computer and use it in GitHub Desktop.
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
(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