項目中需要對漢字使用區位碼進行轉化,寫了一個類,分享如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Rare.Card.Libary.Helper
{
public class CharacterAreaCodingConvertHelper
{
/// <summary>
/// 漢字轉區位碼
/// </summary>
/// <param name="character"></param>
/// <returns></returns>
public static string CharacterToCoding(string character)
{
string coding = string.Empty;
for (int i = 0; i < character.Length; i++)
{
byte[] bytes = System.Text.Encoding.GetEncoding("GB2312").GetBytes(character.Substring(i, 1));
string lowCode = System.Convert.ToString(bytes[0], 16); //取出低位元組編碼內容(兩位16進位)
if (lowCode.Length == 1)
lowCode = "0" + lowCode;
string hightCode = System.Convert.ToString(bytes[1], 16);//取出高位元組編碼內容(兩位16進位)
if (hightCode.Length == 1)
hightCode = "0" + hightCode;
coding += (lowCode + hightCode);//加入到字串中,
}
return coding;
}
/// <summary>
/// 區位碼取漢字
/// </summary>
/// <param name="coding"></param>
/// <returns></returns>
public static string CodingToCharacter(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;
}
return characters;
}
}
}
測試資料:
比如“布”
查出來的是1828
18---0x12 -----0x12+0xa0 = 0xB2
28 ---- 0x1c + 0xA0 ------0xBC
所以“布”的區位碼是B2Bc
字串:張三的區位碼轉化以後是D5C5C8FD