# Javascript Binary to Denary

I wrote this but I am not sure I can use it for the purpose I wanted. Feel free to use if it’s useful to you!

```<html>
<style>
input[type='text'] {
font-size: 24px;
}
</style>
<script type="text/javascript">

// A quick and dirty binary to denary converter in Javascript
// I wrote it to use with Year 9 students but not sure it meets my
// objectives, so here it is for you!
// By @codeboom codeboom.wordpress.com

function generate_denary(form) {
// Generate the denary number by multiplying the digits by their place value and adding together
var denary = 8 * parseInt(form.first.value) +
4 * parseInt(form.second.value) +
2 * parseInt(form.third.value) +
parseInt(form.fourth.value);
form.denary.value = denary;
}

function generate_binary(form){

// Reset the form if they tried to enter a number we can't make with 4 bits
if(form.denary.value > 15) {
alert("That number is too big to make with 4 bits!");
form.denary.value = 1;
form.first.value = 0;
form.second.value = 0;
form.third.value = 0;
form.fourth.value = 1;
}
else {
var binary = "";
var current = form.denary.value;

// Repeatedly divide by 2, see if there is a remainder
// and store it as the binary digit
for(var i=0; i<4; i++){
var digit = current % 2;
binary = digit + binary;
current = Math.floor((current - digit)/2);
}

// Set the values you worked out into the boxes
form.first.value = binary.charAt(0);
form.second.value = binary.charAt(1);
form.third.value = binary.charAt(2);
form.fourth.value = binary.charAt(3);
}

}
</script>

<body>
<form>
<h1>Binary number</h1>
<input type="text" name="first" style="width: 50px;" maxlength="1" onchange="generate_denary(this.form)">
<input type="text" name="second" style="width: 50px;" maxlength="1" onchange="generate_denary(this.form)">
<input type="text" name="third" style="width: 50px;" maxlength="1" onchange="generate_denary(this.form)">
<input type="text" name="fourth" style="width: 50px;" maxlength="1" onchange="generate_denary(this.form)">

<h1>Denary number</h1>
<input type="text" name="denary" onchange="generate_binary(this.form)">
</form>

</body>
</html>
```