How to get ASCII value of characters in C#

大兔子大兔子 提交于 2020-05-15 06:46:19

问题


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.

  • How to get ASCII value of string in C#
  • https://www.codeproject.com/Questions/516802/ConvertingpluscharsplustoplusASCIIplusinplusC

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

Any help/suggestion highly appreciated.


回答1:


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);
}



回答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]}");
        }
    }



回答3:


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);
                }
        }



回答4:


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




回答5:


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



来源:https://stackoverflow.com/questions/43370754/how-to-get-ascii-value-of-characters-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!