Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#.

like image 588
Shamim Hafiz - MSFT Avatar asked Feb 15 '11 11:02

Shamim Hafiz - MSFT


People also ask

How do I get the ASCII code for a character?

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.

What returns the ASCII value of a given character?

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.


2 Answers

Just cast each character to an int:

for (int i = 0; i < str.length; i++)     Console.Write(((int)str[i]).ToString()); 
like image 162
Jorge Córdoba Avatar answered Sep 21 '22 06:09

Jorge Córdoba


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()); 
like image 35
Joel Etherton Avatar answered Sep 19 '22 06:09

Joel Etherton