Converting characters in string to ascii

G

Guest

In C#, how would you loop through each character in a string and convert them
to their ascii values?
 
O

Ollie Riches

do you mean something like this:

static void Main(string[] args)
{
string test = "ollie";
foreach(char c in test)
{
Console.WriteLine((int)c);
}
Console.ReadLine();
}

HTH

Ollie Riches
 
M

Morten Wennevik

Hi Dan,

Use the Encoding class.

byte[] asciicharacters = Encoding.ASCII.GetBytes(unicodeString);
 
G

Guest

This doesn't answer how to convert the character to its numeric ascii value.
While I'm at it, I'd also like to then convert the resulting number to its
hex equivalent.
 
C

Christof Nordiek

you can cast the char to int.
if the value is in the range of 0 to 127 it's the ascii value of the char;
if not it's not a ascii-character.
 
M

Michael A. Covington

This doesn't answer how to convert the character to its numeric ascii
Doesn't System.Encoding get involved here? The string might not be ASCII;
it might be Unicode.

Hex and decimal are not different kinds of numbers. They are different ways
of printing a number. Format strings (String.Format) with the appropriate
specifier can convert a number into the characters that represent it in
either decimal or hex.
 
J

Jon Skeet [C# MVP]

Morten Wennevik said:
Use the Encoding class.

byte[] asciicharacters = Encoding.ASCII.GetBytes(unicodeString);

There's no need to in this case - all ASCII values are the same as in
Unicode, although of course there's much more of Unicode.

Just casting the character to an int will give you the Unicode value -
if it's in the ASCII range, the value will be the ASCII value.
 
J

Jon Skeet [C# MVP]

Michael A. Covington said:
Doesn't System.Encoding get involved here?

No - or at least, it doesn't need to.
The string might not be ASCII; it might be Unicode.

*All* strings are Unicode.

All you've got to know is whether a number is above 127 or not, and
there's no need to get Encoding involved to do that :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top