JS Encoding and Decoding

时间:2022-06-21 20:34:09
//charator Str to Hex
function strToHex(str) {
var rs = "";
for (var i = 0; i < str.length; i++)
rs = (rs == "" ?"":rs + ",")+ str.charCodeAt(i).toString(16);
return rs;
}
//Hex to charator Str
function hexToStr(str) {
var arr = str.split(","),rs="";
for(var i = 0; i < arr.length; i++)
rs += String.fromCharCode(arr[i]);
return rs;
}
function asciiHexToStr(str) {
var symbols = " !\"#$%&'()*+,-./0123456789:;<=>?@" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "[\\]^_`" + "abcdefghijklmnopqrstuvwxyz" + "{|}~";
str = str.toLowerCase();
var hex = "0123456789abcdef";
var text = "";
var i = 0; for (i = 0; i < str.length; i = i + 2) {
var char1 = str.charAt(i);
if (char1 == '') {//分隔符char1== ":";
i++;
char1 = str.charAt(i);
}
var char2 = str.charAt(i + 1);
var num1 = hex.indexOf(char1);
var num2 = hex.indexOf(char2);
var value = num1 << 4;
value = value | num2; var valueInt = parseInt(value);
var symbolIndex = valueInt - 32;
var ch = '?';
if (symbolIndex >= 0 && value <= 126) {
ch = symbols.charAt(symbolIndex)
}
text += ch;
}
return text;
}
function strToAsciiHex(str) {
var symbols = " !\"#$%&'()*+,-./0123456789:;<=>?@" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "[\\]^_`" + "abcdefghijklmnopqrstuvwxyz" + "{|}~";
var hexChars = "0123456789abcdef";
var text = "";
for (i = 0; i < str.length; i++) {
var oneChar = str.charAt(i);
var asciiValue = symbols.indexOf(oneChar) + 32;
var index1 = asciiValue % 16;
var index2 = (asciiValue - index1) / 16;
if (text != "") text += "";//分隔符text += ":";
text += hexChars.charAt(index2);
text += hexChars.charAt(index1);
}
return text;
}