Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Convert A Number To an ASCII Character?

Tags:

I want to create an application where user would input a number and the program will throw back a character to the user.

Edit: How about vice versa, changing a ascii character into number?

like image 914
Cyrax Nguyen Avatar asked Jul 18 '13 17:07

Cyrax Nguyen


People also ask

How do I convert decimal to ASCII manually?

Just add (48) which is (0b00110000), (0x30). If by decimal you mean integer then its very easy. Google ASCII table or something to that effect. It should bring up a chart with all the characters and decimal equivalents.

What is the ASCII code for numbers?

The ASCII Character Set ASCII is a 7-bit character set containing 128 characters. It contains the numbers from 0-9, the upper and lower case English letters from A to Z, and some special characters. The character sets used in modern computers, in HTML, and on the Internet, are all based on ASCII.

What is the ASCII value of 0 to 9?

It can be observed that ASCII value of digits [0 – 9] ranges from [48 – 57]. Therefore, in order to print the ASCII value of any digit, 48 is required to be added to the digit.


2 Answers

You can use one of these methods to convert number to an ASCII / Unicode / UTF-16 character:

You can use these methods convert the value of the specified 32-bit signed integer to its Unicode character:

char c = (char)65; char c = Convert.ToChar(65);  

Also, ASCII.GetString decodes a range of bytes from a byte array into a string:

string s = Encoding.ASCII.GetString(new byte[]{ 65 }); 

Keep in mind that, ASCIIEncoding does not provide error detection. Any byte greater than hexadecimal 0x7F is decoded as the Unicode question mark ("?").

like image 134
Farhad Jabiyev Avatar answered Oct 22 '22 13:10

Farhad Jabiyev


Edit: By request, I added a check to make sure the value entered was within the ASCII range of 0 to 127. Whether you want to limit this is up to you. In C# (and I believe .NET in general), chars are represented using UTF-16, so any valid UTF-16 character value could be cast into it. However, it is possible a system does not know what every Unicode character should look like so it may show up incorrectly.

// Read a line of input string input = Console.ReadLine();  int value; // Try to parse the input into an Int32 if (Int32.TryParse(input, out value)) {     // Parse was successful     if (value >= 0 and value < 128) {         //value entered was within the valid ASCII range         //cast value to a char and print it         char c = (char)value;         Console.WriteLine(c);     } } 
like image 37
Cemafor Avatar answered Oct 22 '22 15:10

Cemafor