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#.
Join Stack Overflow to learn, share knowledge, and build your career.
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#.
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());
ConvertToUTF32()
since that is the true encoding of the characters themselves.
– Joel Etherton
Feb 15 '11 at 13:43
Just cast each character to an int:
for (int i = 0; i < str.length; i++)
Console.Write(((int)str[i]).ToString());
foreach(char c in str.ToCharArray())
– Joel Etherton
Feb 15 '11 at 11:26
foreach (char c in str)
. No need even for the ToCharArray
.
– LukeH
Feb 15 '11 at 15:39
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);
}
string
is a counted sequence of UTF-16 code units (one or two of which encode a Unicode codepoint), this will get the UTF-16 code units. Codepoints are more human readable. To get those, convert to UTF-32 because UTF-32 code units and Unicode codepoints are one-to-one and have the same values.
– Tom Blodget
Feb 26 '16 at 8:36
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);
}