JavaScript转换二进制编码为ASCII码的方法

本文实例讲述了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程序设计有所帮助。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。