Skip to content

Instantly share code, notes, and snippets.

@ronen-e
Created October 1, 2016 21:26
Show Gist options
  • Select an option

  • Save ronen-e/76de7831f844d22e2064e5dea08ead4b to your computer and use it in GitHub Desktop.

Select an option

Save ronen-e/76de7831f844d22e2064e5dea08ead4b to your computer and use it in GitHub Desktop.
Convert to binary from decimal and vice versa
function binToDec(n) {
var result = 0;
var s = n.toString();
var len = s.length - 1;
for (var i = len; i >= 0; i--) {
result += s[i] * Math.pow(2, len-i);
}
return result;
}
/*
example: 1010010
0 * 2^0
1 * 2^1
0 * 2^2
0 * 2^3
1 * 2^4
0 * 2^5
1 * 2^6
result = 82
*/
function decToBin(n) {
var result = '';
// find highest integer power of 2 equal or less then n
var order = Math.floor(Math.log2(n));
while (order >= 0) {
var k = Math.pow(2, order);
// if n >= 2^order - reduce that value from n and add 1 to result
if (n >= k) {
n = n - k;
result += 1;
} else {
// else add 0
result += 0;
}
// reduce order by 1
order = order - 1;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment