using System;
using System.Text;
namespace Test
{
class MainClass
{
/// <summary>
/// 中文空白字符,用于替换空格
/// </summary>
private static string ChineseSpace = " ";
public static void Main(string[] args)
{
string s = "你我是中国人 12 34 ABCabc";
Console.WriteLine(s);
s = ChineseToCoding(s);
Console.WriteLine(s);
s = CodingToChinese(s);
Console.WriteLine(s);
Console.ReadKey();
}
/// <summary>
/// 汉字转区位码方法
/// </summary>
/// <param name="character">汉字</param>
/// <returns>区位码</returns>
public static string ChineseToCoding(string character)
{
string coding = string.Empty;
//空格处理(如不用可以注释)
character = character.Replace(" ", ChineseSpace);
try
{
for (int i = 0; i < character.Length; i++)
{
byte[] bytes = System.Text.Encoding.GetEncoding("GB2312").GetBytes(character.Substring(i, 1));
if (bytes.Length == 2)
{
string lowCode = System.Convert.ToString(bytes[0], 16);
if (lowCode.Length == 1)
lowCode = "0" + lowCode;
string hightCode = System.Convert.ToString(bytes[1], 16);
if (hightCode.Length == 1)
hightCode = "0" + hightCode;
coding += (lowCode + hightCode);
}
else
{
string lowCode = System.Convert.ToString(bytes[0], 16);
if (lowCode.Length == 1)
lowCode = "0" + lowCode;
coding += (lowCode);
}
}
return coding;
}
catch
{
return null;
}
}
/// <summary>
/// 区位码转汉字方法
/// </summary>
/// <param name="coding">区位码</param>
/// <returns>汉字</returns>
public static string CodingToChinese(string coding)
{
string characters = string.Empty;
if (coding.Length % 4 != 0)//编码为16进制,必须为4的倍数。
{
throw new System.Exception("编码格式不正确");
}
for (int i = 0; i < coding.Length / 4; i++)
{
byte[] bytes = new byte[2];
int j = i * 4;
string lowCode = coding.Substring(j, 2); //取出低字节,并以16进制进制转换
bytes[0] = System.Convert.ToByte(lowCode, 16);
string highCode = coding.Substring(j + 2, 2); //取出高字节,并以16进制进行转换
bytes[1] = System.Convert.ToByte(highCode, 16);
string character = System.Text.Encoding.GetEncoding("GB2312").GetString(bytes);
characters += character;
}
//空格复原(将中文空白字符转换普通空格)
characters = characters.Replace(ChineseSpace, " ");
return characters;
}
}
}