字符串转十六进制
2020-05-30 本文已影响0人
曲昶光
字符串转十六进制的步骤
将字符串的每一个元素转成十六进制再拼接在一起
//转16进制
stringToHex (str) {
if (str === "")
return "";
var hexCharCode = [];
hexCharCode.push("0x");
for (var i = 0; i < str.length; i++) {
hexCharCode.push((str.charCodeAt(i)).toString(16));
}
return hexCharCode.join("");
},
// 16进制转回字符串
hexToString (hexCharCodeStr) {
var trimedStr = hexCharCodeStr.trim();
var rawStr =
trimedStr.substr(0, 2).toLowerCase() === "0x"
?
trimedStr.substr(2)
:
trimedStr;
var len = rawStr.length;
if (len % 2 !== 0) {
alert("非法格式的ASCII码!");
return "";
}
var curCharCode;
var resultStr = [];
for (var i = 0; i < len; i = i + 2) {
curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
resultStr.push(String.fromCharCode(curCharCode));
}
return resultStr.join("");
},