简体   繁体   中英

Getting different values from convert char to integer

when I display the 'i' variable, which would be a char value

{
  class Program {
    static void Main(string[] args) {
      var max = 0;
      var lista = new char[] {
        '1',
        '2',
        '3',
        '4'
      };
      foreach(char i in lista) {
        Console.WriteLine(i);
        /* var hola =  Convert.ToInt32(i);
          Console.WriteLine(hola);*/
      }
    }
  }
}

I get this:

> 1 2 3 4

However, when converting 'i' into an int

var max = 0;
var lista = new char[] {
  '1',
  '2',
  '3',
  '4'
};
foreach(char i in lista) {
  var hola = Convert.ToInt32(i);
  Console.WriteLine(hola);
}    
            

I get this:

49 50 51 52

Any idea what could be the problem? I'd like to obtain the same values, so I can evaluate them as integers and obtain the biggest of them, but I can't.

When you convert a char to an int , you get the ASCII value of that character. The neat thing with these values is that they are sequential, so if you subtract the value of '0' (the 0 character ), you can convert a character representing a digit to that digit:

var hola =  i - '0';

If you want the literal character and not the ascii number of the character, use the ToString() method

var hola =  Convert.ToInt32(i.ToString());

WriteLine method internally converts the parameters string. Thus you can have the value you want. ToInt method return the ASCII value of that char. You have to convert your i value to string i.ToString() or you can simply substract 48 from the converted value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM