3

I am getting weird numbers when I am parsing my string using the convert.toint32

var check = "82567";
Convert.ToInt32(check[0]) //I get 56
Convert.ToInt32(check[0].ToString());// I get 8

Can someone help me make sense of this

Tiisetso Tjabane
  • 2,088
  • 2
  • 19
  • 24

2 Answers2

5

check[0] is a single character -- the character '8'. This means that you call the Convert.ToInt32(char) overload, which:

returns a 32-bit signed integer that represents the UTF-16 encoded code unit of the value argument

'8' has the value 56.

check[0].ToString() returns a string, and so you call Convert.ToInt32(string), which returns:

A 32-bit signed integer that is equivalent to the number in value, or 0 (zero) if value is null

canton7
  • 37,633
  • 3
  • 64
  • 77
3

There's nothing wrong here.

Your first call is to Convert.ToInt32(char) which just promotes the char to int. The value of check[0] is a char with a value of 56 - the UTF-16 value of '8'.

Your second call is to Convert.ToInt32(string) which parses the string as a number. The string "8" is parsed to the value 8.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194