日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#字符串和Acsii碼相互轉換_C#教程

作者:新時代丘鳴山 ? 更新時間: 2023-04-08 編程語言

1,現在因為遇到一個讀取pdf文件文本信息遇到亂么問題,才找到這個文本字符串的編碼轉換的實現方式來判斷是否存在亂碼(0>亂碼>255):

C# 字符轉ASCII碼,ASCII碼轉字符

public static int Asc(string character)
{
  if (character.Length == 1)
  {
    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
    int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
    return (intAsciiCode);
  }
  else
  {
    throw new Exception("Character is not valid.");
  }
 
}

ASCII碼轉字符:

public static string Chr(int asciiCode)
{
   if (asciiCode >= 0 && asciiCode <= 255)
   {
      System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
      byte[] byteArray = new byte[] { (byte)asciiCode };
      string strCharacter = asciiEncoding.GetString(byteArray);
      return (strCharacter);
   }
   else
   {
      throw new Exception("ASCII Code is not valid.");
   }
}

還有一個特殊的方式:直接獲取字符串的字節大小來區分

string str="abcd";
byte[] bytetest = System.Text.Encoding.Default.GetBytes(str.ToString());

原文鏈接:https://blog.csdn.net/zyzBulus/article/details/87913453

欄目分類
最近更新