ASCII 轉換幫助類
阿新 • • 發佈:2020-07-20
/// <summary> /// ASCII 幫助類 /// </summary> public static class ASCIIHelper { /// <summary> /// 含中文字串轉ASCII /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Str2ASCII(String str) {//這裡我們將採用2位元組一個漢字的方法來取出漢字的16進位制碼 byte[] textbuf = Encoding.Default.GetBytes(str); //用來儲存轉換過後的ASCII碼 string textAscii = string.Empty; for (int i = 0; i < textbuf.Length; i++) { textAscii += textbuf[i].ToString("X"); }return textAscii; } /// <summary> /// ASCII轉含中文字串 /// </summary> /// <param name="textAscii">ASCII字串</param> /// <returns></returns> public static string ASCII2Str(string textAscii) { int k = 0;//位元組移動偏移量 byte[] buffer = new byte[textAscii.Length / 2];//儲存變數的位元組 for (int i = 0; i < textAscii.Length / 2; i++) { //每兩位合併成為一個位元組 buffer[i] = byte.Parse(textAscii.Substring(k, 2), System.Globalization.NumberStyles.HexNumber); k = k + 2; } //將位元組轉化成漢字 return Encoding.Default.GetString(buffer); } }