Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to ASCII

Tags:

string

c#

ascii

How do I convert each letter in a string to its ASCII character value?

like image 697
Student Avatar asked Mar 18 '11 06:03

Student


People also ask

How do I convert to ASCII in Python?

chr () is a built-in function in Python that is used to convert the ASCII code into its corresponding character. The parameter passed in the function is a numeric, integer type value. The function returns a character for which the parameter is the ASCII code.

Is string an ASCII?

If text is being stored in a computer, it is usually stored as a string (a series of ASCII characters, each one of which is stored as one byte). The formatting characters such as space, carriage return and line feed may be included in the string.


1 Answers

.NET stores all strings as a sequence of UTF-16 code units. (This is close enough to "Unicode characters" for most purposes.)

Fortunately for you, Unicode was designed such that ASCII values map to the same number in Unicode, so after you've converted each character to an integer, you can just check whether it's in the ASCII range. Note that you can use an implicit conversion from char to int - there's no need to call a conversion method:

string text = "Here's some text including a \u00ff non-ASCII character"; foreach (char c in text) {     int unicode = c;     Console.WriteLine(unicode < 128 ? "ASCII: {0}" : "Non-ASCII: {0}", unicode); } 
like image 183
Jon Skeet Avatar answered Oct 09 '22 12:10

Jon Skeet