• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

JavaScript转换二进制编码为ASCII码

JavaScript 水墨上仙 1274次浏览

JavaScript转换二进制编码为ASCII码

<html>
<head>
<script type="text/javascript">
var input_id = "bin_text";
var answer_id = "answer";
function convertToASCII() {
	var bin_text = document.getElementById(input_id);
	var answer = document.getElementById(answer_id);
	if (!answer) {
		alert("Error: No element with id \""+answer_id+"\".");
		return;
	}
	if (bin_text)
		var text = bin_text.value;
	else {
		error("No element with id \""+input_id+"\".");
		return;
	}
	var divisible = text.length % 8;
	var nonBinary = /[^0|1]/.test(text);
	if (text.length > 0 && divisible == 0 && !nonBinary) {
		var regex = /[0|1]{8}/g;
		var str = text.match(regex);
		var code = 0;
		var placeVal, exp, digit;
		var ascii = '';
		while (str.length > 0) {
			code = 0;
			for (var i=0; i<str[0].length; i++) {
				placeVal = 7-i;
				exp = Math.pow(2, i);
				digit = str[0].charAt(placeVal);
				code += exp*digit;
			}
			str.shift();
			ascii += String.fromCharCode(code);
		}
		answer.innerHTML = "<p class=\"binary\">" + ascii + "</p>";
	}
	else {
		error("Malformed binary.");
		return;
	}
	function error(errText) {
		answer.innerHTML = "<span class=\"error\">Error: " + errText + "</span>";
	}
}
</script>
<style type="text/css">
.block {
	width: 45%;
	border: 1px solid #000000;
	padding: 10px;
}
.binary {
	background-color: #C6FFC7;
	padding: 3px;
}
.error {
	background-color: #FFC6C6;
	padding: 3px;
}
</style>
</head>
<body>
<div style="float:left;" class="block">
	<form onSubmit="convertToASCII(); return false;">
		<p>Enter some binary to decode:</p>
		<input type="text" id="bin_text"/>
	</form>
</div>
<div style="float:right;" class="block">
	<p id="answer"><br/></p>
</div>
</body>
</html>


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明JavaScript转换二进制编码为ASCII码
喜欢 (0)
加载中……