Showing posts with label decimal to binary in js. Show all posts
Showing posts with label decimal to binary in js. Show all posts

Friday, October 23, 2015

Decimal To Binary Converter in JavaScript

This simple program that I wrote in JavaScript will ask the user to enter a decimal value and then it will convert it into binary format.

If you  have some questions please send me an email at jake.r.pomperada@gmail.com and jakerpomperada@yahoo.com. My mobile number here in the Philippines is 09173084360.


Sample Program Output

Program Listing

<html>
 <head>
  <title>Decimal To Binary Converter </title>
 </head>
    <body>
<h2> Decimal To Binary Converter </h2>
    <script>
function decimal_to_binary(dec,length){
  var output_result = "";
  while(length--)
    output_result += (dec >> length ) & 1;    
  return output_result;  
}
   
var input = parseInt(prompt("Enter a Number"));
input_solve = decimal_to_binary(input,8);
if (!isNaN(input)) {
  document.write("<h2>" +input + "<sub>10</sub> in decimal is equivalent to " 
  + input_solve + "<sub>2</sub> in binary. </h2>" );
 }
while(isNaN(input)){
input = parseInt(prompt("Please enter a numerical value."));
input_solve =decimal_to_binary(input,8);
if (!isNaN(input)) {
  document.write("<h2>" +input + "<sub>10</sub> in decimal is equivalent to " 
  + input_solve + "<sub>2</sub> in binary.</h2>" );
 }
}
</script>
</body>

</html>