JavaScript实现把十进制非负整数转换为二进制
程序员文章站
2024-03-18 21:46:28
...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IFE ECMAScript</title>
</head>
<body>
<input id="dec-number" type="number" placeholder="输入一个十进制非负整数">
<button id="trans-btn">转化为二进制</button>
<p id="result">运算结果</p>
<script>
function dec2bin(decNumber) {
try {
if (decNumber < 0) {
throw "必须为非负整数";
}
} catch (error) {
return "Error:" + error;
}
var temp = 0;
var num = decNumber;
var arr = new Array();
while (num > 0) {
temp = num % 2;
arr.push(temp);
num = parseInt(num / 2);
}
return arr.reverse().join("");
}
var btn = document.querySelector("#trans-btn");
btn.addEventListener("click", function () {
var aaa = document.getElementById("dec-number").value;
var res = document.getElementById("result");
res.innerHTML = dec2bin(aaa);
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IFE ECMAScript</title>
</head>
<body>
<input id="dec-number" type="number" placeholder="输入一个十进制非负整数">
<input id="bin-bit" type="number" placeholder="输入转化后二进制数字位数">
<button id="trans-btn">转化为二进制</button>
<p id="result">运算结果</p>
<script>
function dec2bin(decNumber, binBit) {
try {
if (decNumber < 0) {
throw "必须为非负整数";
}
} catch (error) {
return "Error:" + error;
}
var temp = 0;
var num = decNumber;
var arr = new Array();
while (num > 0) {
temp = num % 2;
arr.push(temp);
num = parseInt(num / 2);
}
var str = arr.reverse().join("");
var len = str.length;
if (len > binBit) {
console.warn("输入的二进制数字位数太小,按原本的位数显示!");
return str;
}
else {
for (var i = 0; i < binBit-len; i++) { //注意str.length是动态变化的
str = "0" + str;
}
return str;
}
}
var btn = document.querySelector("#trans-btn");
btn.addEventListener("click", function () {
var aaa = document.getElementById("dec-number").value;
var binbit = document.getElementById("bin-bit").value;
var res = document.getElementById("result");
res.innerHTML = dec2bin(aaa, binbit);
});
</script>
</body>
</html>
上一篇: F时分秒转换