Home > OS >  Incorrect cast to char element of a string derived from a number
Incorrect cast to char element of a string derived from a number

Time:06-17

static void Main()
{
    int a = 612345;
    string b = Convert.ToString(a);
    char c = Convert.ToChar(b[0]);
    int d = Convert.ToInt32(c);
    Console.WriteLine(d);
}

When doing this operation, I would like to get the output "6", but I get "54". Going through the program with a debugger, I saw this.

debugger

Where char c generally takes the number 54 if the zero element of the array is 6? How can I fix this?

I apologize in advance if my question seems stupid and incorrect to someone, I am new to programming. (But I understand that from a practical point of view, all these conversions are meaningless. This is precisely the learning task for a better understanding of the language)

CodePudding user response:

Each character has a code, and some characters have corresponding numeric value, e.g.

char : code : value
-------------------
 '0' :   48 :     0
 '6' :   54 :     6
 'A' :   65 :    -1 (default value when character doesn't have numeric value)
 '¾' :  190 :  0.75 (note, that numeric value is a floating point value here) 

So far so good, the most accurate way to obtain the numeric value is char.GetNumericValue:

char c = '¾';
      
double result = char.GetNumericValue(c);

However, in case of '0' .. '9' range you can put it as c - '0', e.g.

char c = '6';
      
int result = c - '0';

In your case

int d = b[0] - '0';

alternative

int d = (int) char.GetNumericValue(b, 0);

CodePudding user response:

54 is the ASCII code of 6. Your problem is because a char is really not that different from a small integer. Do this instead:

int a = 612345;
string b = a.ToString();
int d = Int32.Parse(b[0].ToString());
Console.WriteLine(d);

You can call ToString() on almost anything in C#, so that conversion is easy. Use Int32.Parse to turn your char into an int and call ToString on the char to make Parse accept it, since it doesn't take char.

EDIT To see that char is really just an integer underneath, you can actually change your original code like this:

int d = Convert.ToInt32(c)-'0';

and still get 6.

  • Related