JavaScript转换二进制编码为ASCII码的方法
本文实例讲述了JavaScript转换二进制编码为ASCII码的方法。分享给大家供大家参考。具体如下:
<html> <head> <scripttype="text/javascript"> varinput_id="bin_text"; varanswer_id="answer"; functionconvertToASCII(){ varbin_text=document.getElementById(input_id); varanswer=document.getElementById(answer_id); if(!answer){ alert("Error:Noelementwithid\""+answer_id+"\"."); return; } if(bin_text) vartext=bin_text.value; else{ error("Noelementwithid\""+input_id+"\"."); return; } vardivisible=text.length%8; varnonBinary=/[^0|1]/.test(text); if(text.length>0&&divisible==0&&!nonBinary){ varregex=/[0|1]{8}/g; varstr=text.match(regex); varcode=0; varplaceVal,exp,digit; varascii=''; while(str.length>0){ code=0; for(vari=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="<pclass=\"binary\">"+ascii+"</p>"; } else{ error("Malformedbinary."); return; } functionerror(errText){ answer.innerHTML="<spanclass=\"error\">Error:"+ errText+"</span>"; } } </script> <styletype="text/css"> .block{ width:45%; border:1pxsolid#000000; padding:10px; } .binary{ background-color:#C6FFC7; padding:3px; } .error{ background-color:#FFC6C6; padding:3px; } </style> </head> <body> <divstyle="float:left;"class="block"> <formonSubmit="convertToASCII();returnfalse;"> <p>Entersomebinarytodecode:</p> <inputtype="text"id="bin_text"/> </form> </div> <divstyle="float:right;"class="block"> <pid="answer"><br/></p> </div> </body> </html>
希望本文所述对大家的javascript程序设计有所帮助。