Created
October 1, 2016 21:26
-
-
Save ronen-e/76de7831f844d22e2064e5dea08ead4b to your computer and use it in GitHub Desktop.
Convert to binary from decimal and vice versa
This file contains hidden or 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 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 | |
| */ |
This file contains hidden or 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 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