標籤:
/******************************************************************/ /*********************** ****************************/ /*********************** 漢字轉換工具 ****************************/ /*********************** ****************************/ /******************************************************************/ /**************************** 字串轉編碼函數 **********************************/ private byte[] StringToBytes(string TheString) { Encoding encoding = Encoding.GetEncoding("UTF-8"); Encoding encoding2 = Encoding.GetEncoding("gb2312"); byte[] bytes = encoding.GetBytes(TheString); return Encoding.Convert(encoding, encoding2, bytes); } /**************************** 編碼轉字串函數 **********************************/ private string BytesToString(byte[] Bytes) { Encoding encoding = Encoding.GetEncoding("gb2312"); Encoding encoding2 = Encoding.GetEncoding("UTF-8"); byte[] bytes = Encoding.Convert(encoding, encoding2, Bytes); return encoding2.GetString(bytes); } /**************************** 單擊轉換按鈕事件 **********************************/ private void Changez_Click(object sender, EventArgs e) { if (this.CHcode.Checked)//判斷什麼類型的轉換 { byte[] array = this.StringToBytes(this.intextz.Text); this.outtextz.Text = ""; byte[] array2 = array; for (int i = 0; i < array2.Length; i++) { byte b = array2[i]; string text = b.ToString("x").ToUpper(); TextBox expr_64 = this.outtextz; expr_64.Text = expr_64.Text + "0x" + ((text.Length == 1) ? ("0" + text) : text) + " "; } } else { if (!this.CHcode.Checked) { byte[] array3 = new byte[this.intextz.Text.Length / 2]; try { string text2 = this.intextz.Text; text2 = text2.Replace("0x", ""); text2 = text2.Replace(" ", string.Empty); for (int j = 0; j < text2.Length / 2; j++) { array3[j] = Convert.ToByte(text2.Substring(j * 2, 2), 16); } this.outtextz.Text = this.BytesToString(array3); } catch { MessageBox.Show("資料轉換錯誤,請輸入數字。", "錯誤"); } } } }
c#漢字與編碼之間的轉換(輸出十六進位)