Last active
December 27, 2015 23:09
-
-
Save steinbring/7404064 to your computer and use it in GitHub Desktop.
This very simple HTML + JavaScript app converts decimal numbers to unsigned binary and back again. It can handle values from 0 to 2^64/2. I mostly just did this because I was curious. I doubt it would have much value beyond a CS class or something.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
Joe Steinbring | |
http://steinbring.net | |
11/10/2013 | |
--> | |
<html> | |
<head> | |
<title>Decimal to Binary Converter</title> | |
</head> | |
<body> | |
<h1>Convert between decimal and binary</h1> | |
<p>This is meant to convert unsigned base 2 numbers to base 10 and back again. The maximum number this app can handle is 2^64/2. Hopefully you don't need to worry about anything larger than that. This is written in JavaScript. Feel free to copy it. </p> | |
<form method="post"> | |
<p> | |
<label for="numDecimal">Decimal</label> | |
<input name="numDecimal" type="text" size="25"> | |
</p> | |
<p> | |
<label for="numBinary">Binary</label> | |
<input name="numBinary" type="text" size="25"> | |
</p> | |
<p> | |
<button name="buttDecimalToBinary" type="button" onclick="this.form.numBinary.value = DecimalToBinary(this.form.numDecimal.value);"> | |
Decimal To Binary | |
</button> | |
<button name="buttBinaryToDecimal" type="button" onclick="this.form.numDecimal.value = BinaryToDecimal(this.form.numBinary.value);"> | |
Binary To Decimal | |
</button> | |
</p> | |
</form> | |
<script type="text/javascript"> | |
function DecimalToBinary(DecimalValue){ | |
var BinaryValue = ''; | |
// Loop from 2^64/2 to 1 | |
for (var i=64; i>=1; i--){ | |
// Is 2^i/2 within DecimalValue? | |
if(DecimalValue >= Math.pow(2,i)/2){ | |
// If so, add a 1 to BinaryValue and subtract 2^i/2 from DecimalValue | |
BinaryValue = BinaryValue+'1'; | |
DecimalValue = DecimalValue - (Math.pow(2,i)/2); | |
} | |
else if(BinaryValue.indexOf("1") != -1){ | |
// If not, add a 0, but only if there is already a 1 in the value | |
BinaryValue = BinaryValue+'0'; | |
} | |
} | |
return BinaryValue; | |
} | |
function BinaryToDecimal(BinaryValue){ | |
var DecimalValue = 0; | |
// Flip the character array (aka string) in order to make itterating over it easier | |
BinaryValue = BinaryValue.split("").reverse().join(""); | |
// Loop over BinaryValue (from left to right) | |
for (var i=BinaryValue.length-1;i>=0;i--){ | |
// Is there a 1 in the place? | |
if(BinaryValue[i] == '1'){ | |
// If so, add 2^i/2 to DecimalValue | |
DecimalValue = DecimalValue + (Math.pow(2,i+1)/2); | |
} | |
} | |
return DecimalValue; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment