binary to decimal converter
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Converter</title>
</head>
<body>
<center>
<h2>Converter</h2>
</center>
<div class="flex-container">
<div class="flex-child magenta">
<p>From</p>
<input type="number" style="height: 30px; width: 500px;" id="userInputPk" class="cars" type="text" max="5" placeholder="enter binary here" required></input>
<textarea type="text" id="userInputTextareaPk" rows="4" cols="50" style="width: 500px; height: 300px; margin-top: 10px;"></textarea>
</div>
<div class="in-button">
<input type="button" onclick="convertToBinaryPk()" value="Convert" ><br>
</div>
<div class="flex-child green">
<p>To</p>
<input style="height: 30px; width: 500px;" id="outputPk" class="cars" type="text" readonly></input>
<textarea id="outputTextareaPk" name="w3review" rows="4" cols="50" style="width: 500px; height: 300px; margin-top: 10px;"></textarea>
</div>
</div>
<style>
.flex-container {
display: flex;
}
.flex-child {
flex: 1;
}
.flex-child select{
width: 500px;
height: 30px;
}
#flex-child-green input{
width: 500px;
height: 30px;
}
.in-button input{
width: 80px;
height: 50px;
margin-right: 90px;
margin-top: 80px;
flex: 1;
background-color: blue;
color: white;
border-radius: 5px;
}
.in-button2 input{
width: 80px;
height: 50px;
flex: 1;
background-color: blue;
color: white;
border-radius: 5px;
}
.in-button input:hover{
background-color: white;
color: black;
}
.flex-child:first-child {
margin-right: 20px;
}
</style>
<script type="text/javascript">
var convertToBinaryPk = function(){
var binInput = document.getElementById("userInputPk").value;
document.getElementById("outputTextareaPk").value = checkInputPk(binInput);
}
/* Method to compare whether input conforms to Binary values*/
var checkInputPk = function(input){
if(/[^10]/g.test(input)){
console.log("Value entered is not in binary form");
return "binary inputs only";
} else {
console.log("You've entered a binary number");
return convertToDecimalPk(input);
}
}
var convertToDecimalPk = function(binVal){
var result = 0;
var n = binVal.length - 1;
for (i = 0; i < binVal.length; i++){
var digit = binVal.charAt(i);
result = result + (digit * Math.pow(2, n));
n--;
}
return result;
}
</script>
</body>
</html>

0 Comments