汉字及区位码之间的转换
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Test
{
public partial class HanZiQvWeiMaZhuanHuan : Form
{
public HanZiQvWeiMaZhuanHuan()
{
InitializeComponent();
}
public string CharacterToCoding(char c)
{
//使用GB2312编码
Encoding gb = Encoding.GetEncoding("gb2312");
//将汉字转换为字节
byte[] bytes = gb.GetBytes(new char[] { c });
//一个汉字对应2个字节,如果小于两个字节,则返回错误
if (bytes == null || bytes.Length < 2)
//return "Error";
return Convert.ToString(c);
//取出低字节编码内容(两位16进制)
int nLowCode = Convert.ToInt32(Convert.ToString(bytes[0]), 10);
string sLowCode = Convert.ToString(nLowCode - 160);
if (sLowCode.Length == 1)
sLowCode = "0" + sLowCode;
//取出高字节编码内容(两位16进制)
int nHighCode = Convert.ToInt32(Convert.ToString(bytes[1]), 10);
string sHighCode = Convert.ToString(nHighCode - 160);
if (sHighCode.Length == 1)
sHighCode = "0" + sHighCode;
//组合高位字节和地位字节并返回
return sLowCode + sHighCode;
}
public string CodingToCharacter(string coding)
{
//如果编码不是4位数字,则返回空值
if (coding.Length != 4)
return "";
byte[] bytes = new byte[2];
//提取低位编码到字节数组中
string sLowCode = coding.Substring(0, 2);
int nLowCode = Convert.ToByte(sLowCode, 10) + 160;
bytes[0] = (byte)nLowCode;
//提取高位编码到字节数组中
string sHighCode = coding.Substring(2, 2);
int nHighCode = Convert.ToByte(sHighCode, 10) + 160;
bytes[1] = (byte)nHighCode;
//使用GB2312编码
Encoding gb = Encoding.GetEncoding("gb2312");
//将字节转换为汉字
string sChar = gb.GetString(bytes);
return sChar;
}
//将汉字转换为区位码
private void button1_Click(object sender, EventArgs e)
{
string sChar = textBox1.Text.Trim();
if (sChar.Length > 0)
{
string sCode = CharacterToCoding(sChar[0]);
textBox2.Text = sCode;
}
}
//将区位码转换为汉字
private void button2_Click(object sender, EventArgs e)
{
string sCode = textBox3.Text.Trim();
if (sCode.Length > 0)
{
string sChar = CodingToCharacter(sCode);
textBox4.Text = sChar;
}
}
}
}
posted on 2009-03-24 22:33 VictorShan 阅读(529) 评论(0) 编辑 收藏 举报