Skip to content

Instantly share code, notes, and snippets.

@johnfoderaro
Last active October 14, 2022 09:02
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johnfoderaro/f960aafdaed087a1163c to your computer and use it in GitHub Desktop.
Save johnfoderaro/f960aafdaed087a1163c to your computer and use it in GitHub Desktop.
A simple function to convert a variable value to binary.
function binaryConvert() {
var num = x;
if (num != Math.floor(num)) {
console.log("Please enter a number");
} else if (num < 0) {
console.log("Please enter a positive number");
} else {
var binary = parseInt(num, 10);
console.log(binary.toString(2));
}
}
binaryConvert();
@johnfoderaro
Copy link
Author

  • This script can handle numbers as an integer or string value (e.g., 35 or "35") for var num.
  • It will then check if the variable is an integer (after any JavaScript 'Type Conversions') using Math.floor and then whether or not the variable is less than zero to ensure either zero or a positive value is entered.
  • Finally, it uses parseInt to convert the variable from a string to an integer (if it was indeed entered as a string, in say a web form), followed by toString(2) to convert the variable to a binary value as a string.

@chrisdalao
Copy link

amazing job john

@Bryan-Cee
Copy link

Pretty neat 👍

@lucas-moont
Copy link

Great job

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment