function convert(v,n)
{
return v.toString(n);
}
//十进制的3转换成二进制
console.log(convert(3,2));
//十六进制的a转换成十进制
console.log(parseInt('a', 16));
//二进制的10转换成十进制
console.log(parseInt('10', 2));
用数据结构-栈实现十进制转二进制
我们以100为例子,运算情况如下:
最后结果应从下至上写为:1100100
步骤
1.每次把除以2的余数压入栈。
2.把除以2的结果作为下一次的运算数。
3.重复上面两个步骤直到运算数为0。
<script>
function Stack()
{
this.items=[];
//进栈操作
Stack.prototype.push=function(element){
this.items.push(element);
}
//出栈操作
Stack.prototype.pop=function(){
return this.items.pop();
}
//查看栈顶元素
Stack.prototype.peek=function(){
return this.items[this.items.length-1];
}
//查看栈是否为空
Stack.prototype.isEmpty=function(){
return this.items.length==0;
}
//打印栈
Stack.prototype.toString=function(){
var resultString='';
for(var i=0;i<this.items.length;i++){
resultString+=this.items[i]+' ';
}
return resultString;
}
}
//函数:将十进制转换成二进制
function dec2bin(decNumber)
{
//1.定义栈对象
var stack=new Stack();
//2.循环操作
while(decNumber>0){
//2.1获取余数,并放入到栈中
stack.push(decNumber%2);
//2.2获取整除后的结果用于下一次运算
decNumber=Math.floor(decNumber/2);
}
//从栈中得出0和1
var binaryString='';
while(!stack.isEmpty()){
binaryString+=stack.pop();
}
return binaryString;
}
console.log(dec2bin(100));
</script>