Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Binary Calculator</title>
<style>
body {
text-align:center;
margin:0;
}
#binary, #number, #arithmetic {
padding:10px;
}
#binary a {
padding:2px;
border:1px solid #ccc;
border-radius:2px;
font:normal 20px/20px monospace;
text-decoration:none;
margin:0 5px;
color:#000;
}
#arithmetic {
font:normal 20px/20px monospace;
text-decoration:none;
color:#000;
}
#number {
font:normal 20px/20px monospace;
}
.sep {
font:normal 12px/20px sans-serif;
background:#efefef;
}
</style>
</head>
<body>
<div class='sep'>binary</div>
<div id='binary'></div>
<div class='sep'>arithmetic</div>
<div id='arithmetic'></div>
<div class='sep'>result</div>
<div id='number'>0</div>
<script>
var binary = document.getElementById('binary');
var number = document.getElementById('number');
var value = [];
for (var i = 0; i < 8; i++) {
value.push(0);
var link = binary.insertBefore(document.createElement('a'), binary.firstChild);
link.innerHTML = '' + value[i];
link.href = '#';
link.onclick = (function(i) {
return function() {
value[i] = value[i] == 0 ? 1 : 0;
this.innerHTML = '' + value[i];
var arith = [];
number.innerHTML = value.reduce(function(mem, i, idx) {
arith.push(i * Math.pow(2, idx));
return (i * Math.pow(2, idx)) + mem;
}, 0);
arithmetic.innerHTML = arith.reverse().join(' + ');
return false;
};
})(i);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.