16進制可逆操作類:
public static class Hex16{/// <summary>/// 作用:將字符串內容轉化為16進制數據編碼,其逆過程是Decode/// 參數說明:/// strEncode 需要轉化的原始字符串/// 轉換的過程是直接把字符轉換成Unicode字符,比如數字"3"-->0033,漢字"我"-->U+6211/// 函數decode的過程是encode的逆過程./// </summary>public static string Encode(string strEncode){string strReturn = "";// 存儲轉換后的編碼try{foreach (short shortx in strEncode.ToCharArray()){strReturn += shortx.ToString("X4");}}catch { }return strReturn;}/// <summary>/// 作用:將16進制數據編碼轉化為字符串,是Encode的逆過程/// </summary>public static string Decode(string strDecode){string sResult = "";try{for (int i = 0; i < strDecode.Length / 4; i++){sResult += (char)short.Parse(strDecode.Substring(i * 4, 4),global::System.Globalization.NumberStyles.HexNumber);}}catch { }return sResult;}/// <summary>/// 將數字轉換成16進制字符串,后兩位加入隨機字符,其可逆方法為DecodeForNum/// </summary>public static string EncodeForNum(int id){//用戶加上起始位置后的int startUserIndex = id;//轉換成16進制string hexStr = Convert.ToString(startUserIndex, 16);//后面兩位加入隨機數string randomchars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";string tmpstr ="";//整除的后得到的數可能大于被除數tmpstr += randomchars[(id / randomchars.Length) > randomchars.Length ? randomchars.Length - 1 : (id / randomchars.Length)];//余數不可能大于被除數tmpstr += randomchars[(id % randomchars.Length) > randomchars.Length ? randomchars.Length - 1 : (id % randomchars.Length)];//返回拼接后的字符,轉成大寫string retStr = (hexStr + tmpstr).ToUpper();return retStr;}/// <summary>/// 解密16進制字符串,此方法只適合后面兩位有隨機字符的/// </summary>public static int DecodeForNum(string strDecode){if (strDecode.Length>2){strDecode = strDecode.Substring(0, strDecode.Length - 2);return Convert.ToInt32(strDecode, 16);}return 0;}}
?