Converting characters in string to ascii

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

In C#, how would you loop through each character in a string and convert them
to their ascii values?
 
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
 
Hi Dan,

Use the Encoding class.

byte[] asciicharacters = Encoding.ASCII.GetBytes(unicodeString);
 
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.
 
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.
 
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.
 
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.
 
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 :)
 
Back
Top