Skip to content

Instantly share code, notes, and snippets.

@alexzhou
Created November 11, 2013 07:40
Show Gist options
  • Save alexzhou/7409332 to your computer and use it in GitHub Desktop.
Save alexzhou/7409332 to your computer and use it in GitHub Desktop.
binary clock 二进制时钟
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<style>
.clock .one{
width: 16px;
height: 16px;
background: green;
margin-right: 20px;
}
.clock .zero{
width: 16px;
height: 16px;
background: #ccc;
margin-right: 20px;
}
</style>
<div class="clock">
<h2><b>h</b></h2>
<div id="hour"></div>
</div>
<div class="clock">
<h2><b>m</b></h2>
<div id="min"></div>
</div>
<div class="clock">
<h2><b>s</b></h2>
<div id="sec"></div>
</div>
<script type="text/javascript">
setInterval("setclock()",1000);
function setclock(){
var time = new Date();
var hours = toBin(time.getHours());
var mins = toBin(time.getMinutes());
var secs = toBin(time.getSeconds());
render(hours,'hour');
render(mins,'min');
render(secs,'sec');
}
function toBin(dec) {
var bits = [];
var dividend = dec;
var remainder = 0;
while (dividend >= 2) {
remainder = dividend % 2;
bits.push(remainder);
dividend = (dividend - remainder) / 2;
}
bits.push(dividend);
bits.reverse();
return bits;
}
function render(value,type){
var html = '';
if(type=='hour'){
html = makedot(value,5);
document.getElementById('hour').innerHTML=html;
}else if(type=='min'){
html = makedot(value,6);
document.getElementById('min').innerHTML=html;
}else if(type=='sec'){
html = makedot(value,6);
document.getElementById('sec').innerHTML=html;
}
}
function makedot(value,nums){
var i=null;
var html = '';
var length = value.length;
for(var i = 0;i<length;i++){
if(value[i]){
html = html+'<span class="one">&nbsp;&nbsp;</span>';
}else{
html = html+'<span class="zero">&nbsp;&nbsp;</span>';
}
}
while(length < nums){
html = '<span class="zero">&nbsp;&nbsp;</span>'+html;
length++;
}
return html;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment