开发者

Getting The ASCII Value of a character in a C# string

Consider the string:

string str="A C# string";

What would be most efficient way to printout the ASCII value of each 开发者_运维问答character in str using C#.


Just cast each character to an int:

for (int i = 0; i < str.length; i++)  
  Console.Write(((int)str[i]).ToString());


Here's an alternative since you don't like the cast to int:

foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
    Console.Write(b.ToString());


This example might help you. by using simple casting you can get code behind urdu character.

string str = "عثمان";
        char ch = ' ';
        int number = 0;
        for (int i = 0; i < str.Length; i++)
        {
            ch = str[i];
            number = (int)ch;
            Console.WriteLine(number);
        }


Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
    return GetAsciiVal(s[index]);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
    return unchecked(c & 0xFF);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜