UTF-8 和 gb2312编码转换
/// <summary> /// 编码转换 /// </summary> /// <param name="TheString">字符</param> /// <returns></returns> private byte[] StringToBytes(string TheString) { Encoding FromEncoding = Encoding.GetEncoding("UTF-8"); Encoding ToEncoding = Encoding.GetEncoding("gb2312"); byte[] FromBytes = FromEncoding.GetBytes(TheString); byte[] Tobytes = Encoding.Convert(FromEncoding,ToEncoding,FromBytes);//编码转换 return Tobytes; } /// <summary> /// 编码转换 /// </summary> /// <param name="TheString">字符</param> /// <returns></returns> private string BytesToString(byte[] FromBytes) { Encoding FromEncoding = Encoding.GetEncoding("gb2312"); Encoding ToEncoding = Encoding.GetEncoding("UTF-8"); byte[] Tobytes = Encoding.Convert(FromEncoding, ToEncoding, FromBytes);//编码转换 string str = ToEncoding.GetString(Tobytes); return str; } /// <summary> /// 字符串 转换为 gb2312 编码 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { byte[]by = StringToBytes(this.textBox1.Text); for (int i = 0; i < by.Length;i++ ) { string vv = by[i].ToString("X"); textBox2.AppendText("0x" + (vv.Length==1?"0"+vv:vv) +" " ); } } /// <summary> /// gb2312 编码 转换为 字符串 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { string str = this.textBox2.Text.Replace("0x", "").Replace(" ", ""); ; byte[] by = new byte[str.Length / 2]; for (int i = 0; i < str.Length / 2;i++ ) { string vv = str.Substring(i*2,2); by[i] =Convert.ToByte(vv,16); } string tt = BytesToString(by); this.textBox1.Text = tt; }