Skip to content

Instantly share code, notes, and snippets.

@wbhob
Created August 27, 2018 14:34
Show Gist options
  • Save wbhob/38a136a32002e758e8e7ce9fa838efbd to your computer and use it in GitHub Desktop.
Save wbhob/38a136a32002e758e8e7ce9fa838efbd to your computer and use it in GitHub Desktop.
Make any base-10 integer binary
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