-2

The title says everything. I'm trying to convert char into int in visual studio.

I have already tried this:

int a;
a = (int)x;
System.Console.WriteLine(a);

but it's not giving me anything besides this(from trying to understand the code): 114117105

1 Answers1

1

This will just work:

//a char is a 16-bit numerical value
//usually used for the representation of characters
//here I assign 'a' to it; keep in mind; 'a' has also a numeric representation
//i.e.: 97
char x = 'a';

int a;

//the `int a` is an integer and, through a cast, receives the numeric value
//besides the bit-width (debatable) the data contents are the same.
//If we assign it to an `int` only the "purpose" c.q. representation will change
a = (int)x;

//since we put in an `int` a number will be shown (because of it's purpose)
//if we put in x, then `a` will be shown.
System.Console.WriteLine(a);

Output

97

As you have understand by now; a string, is an array of chars. Therefore a string is hard to represent by a single number, because it is 2 dimensional.

It would be the same as saying, convert: 0,4,43434,878728,3477,3.14159265 to a single number.

https://dotnetfiddle.net/qSYUdP

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/char

On why the output for a is 97; you can look it up in the character table, e.g.: ascii.

Please note that the actual character that is outputted is determined by the chosen font/character table. For most fonts the ASCII is implemented, but it's not guaranteed. So, 97 will not always produce a.

Stefan
  • 17,448
  • 11
  • 60
  • 79