Cyberherbalist
Cyberherbalist

Reputation: 12309

How does one get the ASCII number of a given char?

I need the ASCII value of each character in a string. I know how to convert the string into a byte array so I can loop through each character, but how do I get the ASCII value of each byte?

In the code below...

string s = Console.ReadLine();
byte[] chars = Encoding.UTF8.GetBytes(s);
for (int x = 0; x < chars.Length; x++)
{
    Console.Write(chars[x].ToString() + " ");
}

I can definitely get string representations of each character's ASCII value. I could then add the Convert function to it and be home free...

Console.Write(Convert.ToInt32(chars[x].ToString()));

But this seems needlessly wordy - there must be a function that would take each byte and give me the ASCII code number. What is it?

Upvotes: 2

Views: 334

Answers (2)

FlyingFoX
FlyingFoX

Reputation: 3509

Select may be an easy way to write what you want to do:

string s = Console.ReadLine();
byte[] chars = Encoding.UTF8.GetBytes(s);
int[] ascii = chars.Select(ch => (int)ch).ToArray();

and if you want to write the int[] values somewhere you could use String.Join like this:

string asciiString = String.Join(ascii, ", ");

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Console.Write("{0} ", (int)chars[x]);

or as stated by others in the community:

string s = Console.ReadLine();
for (int x = 0; x < s.Length; x++)
{
    Console.Write("{0} ", (int)s[x]);
}

Upvotes: 4

Related Questions