js 汉字ASCII相互转换

<html>
<head>
<title>transform between native and ascii</title>
</head>

<script type="text/javascript"><!--

var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";

function native2ascii(strNative) {
var output = "";
for (var i=0; i<strNative.length; i++) {
var c = strNative.charAt(i);
var cc = strNative.charCodeAt(i);
if (cc > 0xff)
output += "\\u" + toHex(cc >> 8 ) + toHex(cc & 0xff);
else
output += c;
}
return output;
}

var hexChars = "0123456789ABCDEF";
function toHex(n) {
var nH = (n >> 4) & 0x0f;
var nL = n & 0x0f;
return hexChars.charAt(nH) + hexChars.charAt(nL);
}

function ascii2native(strAscii) {
var output = "";
var posFrom = 0;
var posTo = strAscii.indexOf("\\u", posFrom);
while (posTo >= 0) {
output += strAscii.substring(posFrom, posTo);
output += toChar(strAscii.substr(posTo, 6));
posFrom = posTo + 6;
posTo = strAscii.indexOf("\\u", posFrom);
}
output += strAscii.substr(posFrom);
return output;
}

function toChar(str) {
if (str.substr(0, 2) != "\\u") return str;

var code = 0;
for (var i=2; i<str.length; i++) {
var cc = str.charCodeAt(i);
if (cc >= 0x30 && cc <= 0x39)
cc = cc - 0x30;
else if (cc >= 0x41 && cc <= 0x5A)
cc = cc - 0x41 + 10;
else if (cc >= 0x61 && cc <= 0x7A)
cc = cc - 0x61 + 10;

code <<= 4;
code += cc;
}

if (code < 0xff) return str;

return String.fromCharCode(code);
}
//--></script>

<body style="font-family: 宋体">

<form name="theForm">

Type in the message here, and click a command button:
<br />

<textarea name="theText" cols="80" rows="20" wrap="off"></textarea>
<br />
<input type="button" value="native to ascii" οnclick="document.theForm.theText.value=native2ascii(document.theForm.theText.value);">
    
<input type="button" value="ascii to native"
onclick ="document.theForm.theText.value=ascii2native(document.theForm.theText.value);">

</form>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值