32

How do I convert each letter in a string to its ASCII character value?

1
  • Each letter is already it's ASCII character value. Commented Jan 24, 2013 at 3:55

8 Answers 8

34

.NET stores all strings as a sequence of UTF-16 code units. (This is close enough to "Unicode characters" for most purposes.)

Fortunately for you, Unicode was designed such that ASCII values map to the same number in Unicode, so after you've converted each character to an integer, you can just check whether it's in the ASCII range. Note that you can use an implicit conversion from char to int - there's no need to call a conversion method:

string text = "Here's some text including a \u00ff non-ASCII character";
foreach (char c in text)
{
    int unicode = c;
    Console.WriteLine(unicode < 128 ? "ASCII: {0}" : "Non-ASCII: {0}", unicode);
}
Sign up to request clarification or add additional context in comments.

Comments

25

For Any String try this:

string s = Console.ReadLine();
foreach( char c in s)
{
    Console.WriteLine(System.Convert.ToInt32(c));
}
Console.ReadKey();

3 Comments

what if the string has unicode chars ,what does above code print?
@Srinivas: See my answer for more details - and an alternative to calling Convert.ToInt32.
Using an Int32 (4 bytes) to represent an ASCII char requiring 1 byte. Doesn't look like this response should be marked as best response.
7
byte[] bytes = Encoding.ASCII.GetBytes(inputString);

In the ASCII enconding each char is represented with 1 byte, however in C# the string type uses 2 bytes per char. This happens because .NET uses UTF-16 to encode the text in a string. https://learn.microsoft.com/en-us/dotnet/standard/base-types/character-encoding-introduction

Hence, if you want to keep an ASCII "string" in memory, the most efficient way is to use a byte array. You can always convert it back to string, but remember it will double in size in memory because as soon as it is converted to String it gets converted to UTF-16.

string value = new ASCIIEncoding().GetString(bytes);

Comments

4

Try Linq:

Result = string.Join("", input.ToCharArray().Where(x=> ((int)x) < 127));

This will filter out all non ascii characters. Now if you want an equivalent, try the following:

Result = string.Join("", System.Text.Encoding.ASCII.GetChars(System.Text.Encoding.ASCII.GetBytes(input.ToCharArray())));

Comments

1

I think this code may be help you:

string str = char.ConvertFromUtf32(65)

2 Comments

you should adapt your answer!
Although it did not answer the original question, it was exactly what I needed. Thank you very much for your wrong post.
1

Here is an extension method based on Jon Skeet's answer:

    public static string ConvertUnicodeStringToAscii(this string text)
    {
        var sb = new StringBuilder();
        foreach (char c in text)
        {
            int unicode = c;
            if (unicode < 128)
            {
                sb.Append(c);
            }
        }
        return sb.ToString();
    }

Comments

0

Use Convert.ToInt32() for conversion. You can have a look at How to convert string to ASCII value in C# and ASCII values.

1 Comment

There's no need to call a method. There's an implicit conversion from char to int.
0

You can do it by using LINQ-expression.

  public static List<int> StringToAscii(string value)
  {
        if (string.IsNullOrEmpty(value))
            throw new ArgumentException("Value cannot be null or empty.", nameof(value));

        return value.Select(System.Convert.ToInt32).ToList();
  } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.