数据操作时,设计的各种类型的编码和解码方法
1 转换escape编码,解码Escape
/// <summary>
/// 转换escape编码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private static string Escape(string s)
{
StringBuilder sb = new StringBuilder();
byte[] ba = System.Text.Encoding.Unicode.GetBytes(s);
for (int i = 0; i < ba.Length; i += 2)
{ /**/ BE SURE 2's
sb.Append("%u");
sb.Append(ba[i + 1].ToString("X2"));
sb.Append(ba[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// 解码Escape
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string UnEscape(string str)
{
if (!string.IsNullOrEmpty(str))
{
str = str.Remove(0, 2);//删除最前面两个"%u"
string[] strArr = str.Split(new string[] { "%u" }, StringSplitOptions.None);//以子字符串"%u"分隔
byte[] byteArr = new byte[strArr.Length * 2];
for (int i = 0, j = 0; i < strArr.Length; i++, j += 2)
{
byteArr[j + 1] = Convert.ToByte(strArr[i].Substring(0, 2), 16); //把十六进制形式的字串符串转换为二进制字节
byteArr[j] = Convert.ToByte(strArr[i].Substring(2, 2), 16);
}
str = System.Text.Encoding.Unicode.GetString(byteArr); //把字节转为unicode编码
}
return str;
}
2 unicode编码,unicode解码
/// <summary>
/// unicode编码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToUnicodeString(this string str)
{
StringBuilder strResult = new StringBuilder();
if (!string.IsNullOrEmpty(str))
{
for (int i = 0; i < str.Length; i++)
{
strResult.Append("\\u");
strResult.Append(((int)str[i]).ToString("x"));
}
}
return strResult.ToString();
}
/// <summary>
/// unicode解码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string FromUnicodeString(this string str)
{
//最直接的方法Regex.Unescape(str);
StringBuilder strResult = new StringBuilder();
if (!string.IsNullOrEmpty(str))
{
string[] strlist = str.Replace("\\", "").Split('u');
try
{
for (int i = 1; i < strlist.Length; i++)
{
int charCode = Convert.ToInt32(strlist[i], 16);
strResult.Append((char)charCode);
}
}
catch (FormatException ex)
{
return Regex.Unescape(str);
}
}
return strResult.ToString();
}
3 Url编码和解码,
string str2 =System.Web.HttpUtility.UrlEncode(str1,Encoding.GetEncoding("GB2312"));//这个是对字符串进行编码
//string str2 = System.Web.HttpUtility.UrlDecode(str1, Encoding.GetEncoding("GB2312"));