2013年6月5日 星期三

C# ASCII字碼轉換應用

C# ASCII字碼轉換應用

如何將英文字母大寫”A”轉換為”65”與如何將”65”轉換為英文字母大寫的”A”。
下列範例中RetAsciiCode將大寫”A”轉換成”65”後return給呼叫RetAsciiCode的原程序變數,另外RetAsciiChar帶入一個數字(asciiCode)例如”65”,轉換成大寫”A”並將結果return給呼叫的原程序變數。

C#:
  1. int intAsciiCode = Int32.Parse(RetAsciiCode(“A”)); //回傳數字65
  2. string strAsciiChar = RetAsciiChar(65); //回傳大寫A
  3.  
  4. public int RetAsciiCode(string MyString)
  5. {
  6. if (MyString.Length == 0)
  7. return 0;
  8. else if (MyString.Length > 1)
  9. MyString = MyString[0].ToString();
  10.  
  11. int AsciiCodeO = (int)System.Convert.ToChar(MyString);
  12. byte[] AsciiCodeB = System.Text.Encoding.ASCII.GetBytes(MyString);
  13. //int AsciiCode = System.Convert.ToInt32(AsciiCodeB);
  14. return AsciiCodeO;
  15. }
  16.  
  17. public string RetAsciiChar(int AsciiCode)
  18. {
  19. return System.Convert.ToChar(AsciiCode).ToString();
  20. }

沒有留言:

張貼留言