1

Here is what I've tried

            int two = 2;
            int asciiX = (int) 'x';
            int asciiTwo = (int) two;
            Console.WriteLine("The ascii value of 2 is " + asciiTwo);
            Console.WriteLine("The ascii value of x is " + asciiX););

I expected the output to be 50 as the ascii value of 2 is 50 (which is the ASCII code of '2')

But I got this result :

The ascii value of 2 is 2
The ascii value of x is 120 (it's working for x)

I know that if I put int asciiTwo = '2'; it will works, but it's not directly processing from the variable how can I do, to get the ascii code of a number which is in a int variable ?

0

2 Answers 2

1

two is an int with value 2. You are casting an int to an int. That does not change anything.

You can get the ASCII value using two ways at least:

(int)(two.ToString())[0] //the first char of the string representation of two
(int)(two + '0') //numbers start at '0' in the ASCII table
Sign up to request clarification or add additional context in comments.

Comments

0

You declare the two variable as int. The int of an int is the int itself.

What you want is to declare it as char or string, too.

char two = '2';
int asciiTwo = (int) two;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.