js字符串编码与c#字符解码,简易版
jnsimcode.cs
//2017-5-15 ijunxiong@126.com String.prototype.padLeft = function (len, char) { var s = this; for (var i = 0; i < len - this.length; i++) { s = char + s; } return s; } var jnsimcode = new (function () { this.encode = function (str) { if (str === "") return ""; var hexCharCode = []; for (var i = 0; i < str.length; i++) { hexCharCode.push((str.charCodeAt(i)).toString(16).padLeft(4, '0')); } return hexCharCode.join(""); } this.decode = function (rawStr) { var len = rawStr.length; if (len % 4 !== 0) { //alert("Illegal Format ASCII Code!"); return ""; } var curCharCode = 0; var resultStr = []; for (var i = 0; i < len; i += 4) { curCharCode = parseInt(rawStr.substr(i, 4), 16); resultStr.push(String.fromCharCode(curCharCode)); } return resultStr.join(""); } })();
JnSimCode.cs
//ijunxiong@126.com public class JnSimCode { public static string Decode(string rawStr) { int len = rawStr.Length; if (len % 4 != 0) { return "error!"; } int curCharCode = 0; List<string> resultStr = new List<string>(); for (int i = 0; i < len; i += 4) { curCharCode = Convert.ToInt32(rawStr.Substring(i, 4), 16); resultStr.Add(Convert.ToString((char)curCharCode)); } return string.Concat(resultStr).Replace("\n", "\r\r").Replace("\r\r", "\r\n"); } }
原理:
js,把字符串,每个字符都理解为四字节,之后再16进制编码,即用FFFF表示一个字符,当然这样长度就变得比较长了,但可以解决js交互net服务时的转码乱码问题,