SoFunction
Updated on 2025-03-06

Convert C# strings and Acsii codes to each other

1. Now, because I encountered a problem of reading the text information of a pdf file, I found the implementation method of encoding conversion of this text string to determine whether there is garbled code (0>garbled code>255):

C# character to ASCII code, ASCII code to character

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

ASCII code conversion characters:

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

There is also a special way: directly obtain the byte size of the string to distinguish

string str="abcd";
byte[] bytetest = (());

This is the article about the conversion of C# strings and Acsii codes. For more related content on C# strings and Acsii codes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!