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#.
Program to Print ASCII Value In this program, the user is asked to enter a character. The character is stored in variable c . When %d format string is used, 71 (the ASCII value of G ) is displayed. When %c format string is used, 'G' itself is displayed.
We can also find the character from a given ASCII value using chr() function. This function accepts the ASCII value and returns the character for the given ASCII value.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With