Created
August 27, 2018 14:34
-
-
Save wbhob/38a136a32002e758e8e7ce9fa838efbd to your computer and use it in GitHub Desktop.
Make any base-10 integer binary
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 makeBinary() { | |
var str = ''; | |
// get input from form field | |
var input = +document.getElementById('number').value; | |
// try subtracting every place in a 32-bit integer | |
for (var i = 32; i > -1; i--) { | |
var raised = Math.pow(2,i); | |
if (input - raised > -1) { | |
str += '1'; | |
input -= raised; | |
} else { | |
str += '0'; | |
} | |
} | |
// erase trailing zeroes | |
while (str.substr(0, 1) == '0') { | |
str = str.substr(1); | |
} | |
document.write(str); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment