javascirpt: 十进制与二进制之间的相互转换算法

十进制转换二进制:

 1     var c= 0,i = 10,k;
 2     var g = new Array();
 3 
 4     while(i!=0) {
 5         k = i%2;
 6         if(k != 0) {
 7             i = i-k;
 8         }
 9         g.unshift(k);
10         i=i/2;
11     }
12 
13     for(var kk in g) {
14         document.write(g[kk])
15     }

二进制转换十进制:

 1 var num = 10010010;
 2     var n = 0,i,tmp,result = 0;
 3     while(num!=0) {
 4         tmp = num%10;
 5         if(tmp == 1) {
 6             num = num -1;
 7         }
 8         if(num == 1) {
 9             result = result + num*Math.pow(2,n);
10         }
11         num = num/10;
12         result = result + tmp*Math.pow(2,n);
13         n++;
14         document.write(num + "</br>");
15     }
16     document.write(result);
posted @ 2012-11-25 19:57  fhefh  阅读(566)  评论(0编辑  收藏  举报