1. 程式人生 > >漢字轉Unicode碼 互轉

漢字轉Unicode碼 互轉

漢字轉Unicode碼,涉及的知識點:

1、“x”則代表十六進位制,“x4”代表十六進位制表示的可控制長度,如果長度不夠,則用前導的0填補。2、Unicode寫法:在表示一個Unicode的字元時,通常會用“U+”然後緊接著一組十六進位制的數字來表示這一個字元。3、 ASCII 碼(American Standard Code for Information Interchange,全稱美國資訊交換標準碼)基本的 ASCII 字符集共有 128 個字元,其中有 96 個可列印字元,包括常用的字母、數字、標點符號等,另外還有 32 個控制字元。     0~31及127(共33個)是控制字元或通訊專用字元(其餘為可顯示字元),如控制符:LF(換行)、CR(回車)、FF(換頁)、DEL(刪除)、BS(退格)、BEL(振鈴)等;通訊專用字元:SOH(文頭)、EOT(文尾)、ACK(確認)等;ASCII值為8、9、10和13分別轉換為退格、製表、換行和回車字元。它們並沒有特定的圖形顯示,但會依不同的應用程式而對文字顯示有不同的影響。     32~126(共95個)是字元(32sp是空格),其中48~57為0到9十個阿拉伯數字,65~90為26個大寫英文字母,97~122為26個小寫字母,其餘為一些標點符號、運算子號等。
//轉成16進位制->Unicode  小端
public static string GetUnicode(string ChinaStrText)
{
    string result = "";
    for (int i = 0; i < ChinaStrText.Length; i++)
    {
        if ( (int)ChinaStrText[i] < 127)            //(int)ChinaStrText[i] > 32 &&
        {
            result += string.Format("{0:x2}", (int)ChinaStrText[i]) + "00";
        }
        else
        {
            string temp = string.Format("{0:x4}", (int)ChinaStrText[i]);
            result += temp.Substring(2, 2) + temp.Substring(0, 2);
        }
    }
    return result;
}

將Unicode碼轉成漢子字串

/// <summary>
/// 將Unicode編碼轉換為漢字字串
/// </summary>
/// <param name="UnicodeStr">Unicode編碼字串</param>
/// <returns>漢字字串</returns>
public static string ToGB2312(string UnicodeStr)
{

    StringBuilder rest = new StringBuilder();
    for(int i =0 ; i < UnicodeStr.Length/4; i++)
    {
        string SplitWord = UnicodeStr.Substring(i * 4, 4);

         byte[] codes = new byte[2];
         int code = Convert.ToInt32(SplitWord.Substring(0, 2), 16);
         int code2 = Convert.ToInt32(SplitWord.Substring(2), 16);

         codes[0] = (byte)code;
         codes[1] = (byte)code2;

         rest.Append(Encoding.Unicode.GetString(codes));
    }
    return rest.ToString();
}