一個代碼轉換的類

來源:互聯網
上載者:User
    /**//// <summary>
    /// 代碼轉換功能
    /// </summary>
    public class CodingChange
  {
        /**//// <summary>
        /// 把字元型轉換成16進位編碼
        /// </summary>
        /// <param name="character">字串</param>
        /// <returns>一個字元轉成4位編碼</returns>
      public static string CharacterToCoding(string character)
      {
          string coding = "";
          for (int i = 0; i<character.Length; i++ )
          {
                //取出二進位編碼內容
              byte[] bytes = System.Text.Encoding.Unicode.GetBytes(character.Substring(i,1)); 
              //取出低位元組編碼內容(兩位16進位)    
                string lowCode = System.Convert.ToString(bytes[0], 16); 
              if (lowCode.Length == 1)
                  lowCode = "0" + lowCode;
                //取出高位元組編碼內容(兩位16進位)
              string hightCode = System.Convert.ToString(bytes[1], 16);
              if (hightCode.Length == 1)
                  hightCode = "0" + hightCode;
              coding += (lowCode + hightCode); //加入到字串中
          }
          return coding;
      }

        /**//// <summary>
        /// 把16進位編碼轉換成字元型
        /// </summary>
        /// <param name="coding">4位轉成一位,長度必須是4的倍數</param>
        /// <returns>字串</returns>
      public static string CodingToCharacter(string coding)
      {
          string characters = "";
            if (coding.Length % 4 != 0)//編碼為16進位,必須為4的倍數。
          {
              throw new System.Exception("編碼格式不正確");
          }
          for (int i = 0; i<coding.Length; i+=4 ) //每四位為一個漢字
          {
              byte[] bytes = new byte[2];
              string lowCode = coding.Substring(i, 2); //取出低位元組,並以16進位進位轉換
              bytes[0] = System.Convert.ToByte(lowCode, 16);
              string highCode = coding.Substring(i + 2, 2); //取出高位元組,並以16進位進行轉換
              bytes[1] = System.Convert.ToByte(highCode, 16);
              string character = System.Text.Encoding.Unicode.GetString(bytes);
              characters += character;
          }
          return characters;
      }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.