3

Below is my string in C# which I am converting it to Character array & in need to get the ASCII value of each character in the string.

static void Main(string[] args)
    {
        string s = "Test";
        var arr = s.ToCharArray();
        foreach(var a in arr)
        {
            var n = Encoding.ASCII.GetByteCount(a.ToString());
            Console.WriteLine(a);
            Console.WriteLine(n);
        }
    }

This outputs as

T
1
e
1
s
1
t
1

On googling I got number of links but none of them suffice my need.

I am in need to get the ASCII value of each character in string.???

Any help/suggestion highly appreciated.

Community
  • 1
  • 1
Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • See: http://stackoverflow.com/questions/5002909/getting-the-ascii-value-of-a-character-in-a-c-sharp-string – NoChance Apr 12 '17 at 13:23

5 Answers5

3

A string can be directly enumerated to a IEnumerable<char>. And each char can be casted to a integer to see its UNICODE "value" (code point). UTF-16 maps the 128 characters of ASCII (0-127) to the UNICODE code points 0-127 (see for example https://en.wikipedia.org/wiki/Code_point), so you can directly print this number.

string s = "Test";
foreach (char a in s)
{
    if (a > 127)
    {
        throw new Exception(string.Format(@"{0} (code \u{1:X04}) is not ASCII!", a, (int)a));
    }
    Console.WriteLine("{0}: {1}", a, (int)a);
}
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • Yes.Correct Yours & Matt both ans suffice my need. I am upvoting your post but I have to accept one ans. Can you please check his post & add inputs which is better . I think your is better because it doesn;t involve an extra method calling What you say – Kgn-web Apr 12 '17 at 13:32
  • 1
    I like the exception! But, you are putting a single UTF-16 code unit by itself into the message string, which might be valid in .NET but breaks some expectations. If you format it as `String.Format(@"\u{0:X04}…", (int)a)` then it would still be understood. – Tom Blodget Apr 12 '17 at 16:41
2

Every character is represented in the ASCII table with a value between 0 and 127. Converting the chars to an Integer you will be able to get the ASCII value.

 static void Main(string[] args)
        {
            string s = "Test";
             for (int i = 0; i < s.Length; i++)
                {
                    //Convert one by one every leter from the string in ASCII value.
                    int value = s[i];
                    Console.WriteLine(value);
                }
        }
rm -rf .
  • 473
  • 1
  • 4
  • 14
  • 2
    While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Adam Apr 12 '17 at 15:08
2

GetByteCount will return the count of bytes used, so for each character it will be 1 byte.

Try GetBytes

  static void Main(string[] args)
    {
        string s = "Test";
        var n = ASCIIEncoding.ASCII.GetBytes(s);
        for (int i = 0; i < s.Length; i++)
        {                
            Console.WriteLine($"Char {s[i]} - byte {n[i]}");
        }
    }
Matt
  • 1,436
  • 12
  • 24
  • Yes.Correct Yours & xanatos both ans suffice my need. I am upvoting your post but I have to accept one ans. Can you please check his post & add inputs which is better – Kgn-web Apr 12 '17 at 13:29
  • I think his suggestion is better because he doesn't involve a extra method. – Kgn-web Apr 12 '17 at 13:30
  • Oh..Take care mate. & Please upvote my post if you find it worth? Thanks for sharing your inputs – Kgn-web Apr 12 '17 at 13:31
  • Yes his may be more efficient. – Matt Apr 12 '17 at 14:40
  • This one will silently replace characters (codepoints) that are not in the ASCII character set with '?' (which is). You could still use this technique and get an exception instead if you prefer `Encoding.GetEncoding("US-ASCII", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback).GetBytes("…")`. – Tom Blodget Apr 12 '17 at 16:47
0

You're asking for the byte count when you should be asking for the bytes themselves. Use Encoding.ASCII.GetBytes instead of Encoding.ASCII.GetByteCount. Like in this answer: https://stackoverflow.com/a/400777/3129333

Community
  • 1
  • 1
RonyHe
  • 890
  • 8
  • 11
0
Console.WriteLine(a);   
Console.WriteLine(((int)a).ToString("X"));

You need to convert in int and then in hex.

GetByteCount will return the count of bytes used, so for each character it will be 1.

You can read also: Need to convert string/char to ascii values

Community
  • 1
  • 1
Emanuele
  • 648
  • 12
  • 33