javascript将二进制转换成ASCII码对应的字符

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它实现了将二进制转换为ASCII码对应的字符。

代码实例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<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(answer_id);
    return;
  }
  if (bin_text){
    var text = bin_text.value;
  }
  else {
    error(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 = ascii;
  }
  else {
    error("Malformed binary.");
    return;
  }
  function error(errText) {
    answer.innerHTML = errText ;
  }
}
window.onload=function(){
  var obt=document.getElementById("bt");
  obt.onclick=function(){convertToASCII()}
}
</script>
</head>
<body>
<div>
  <input type="text" value="01101000" id="bin_text"/>
  <input type="button" id="bt" value="查看效果"/>
</div>
<p id="answer"></p>
</body>
</html>
网站出售中,有意者加微信:javadudu

回复

我来回复
  • 暂无回复内容