none
C#:Convert.ToInt32 isn't working properly!!!!! RRS feed

  • Question

  • I have a strange problem that I cant explain in my project, please help!!!!

    string dat = "115";
    Console.WriteLine(Convert.ToInt32(dat[0]));

    The output is: 49

    I thought the output need to be 1 and not 49, instead of dat[0] I tried dat[2] but the output is 53, I saw that 1 + 4 = 5 and 49 + 4 = 53

    so to fix this I wrote:

    string dat = "115";
    Console.WriteLine(Convert.ToInt32(dat[0]) - 48);

    and the output as I expected: 1

    but can someone explain the problem, I cant understand why it is happening.

    thanks.

    Tuesday, August 14, 2018 3:27 PM

Answers

  • Try this:

    string dat = "115";
    //Console.WriteLine(Convert.ToInt32(dat[0]));
    Console.WriteLine(Convert.ToInt32(dat[0].ToString()));
    

    - Wayne

    • Marked as answer by captain4gamer Tuesday, August 14, 2018 3:56 PM
    Tuesday, August 14, 2018 3:37 PM

  • string dat = "115";
    Console.WriteLine(Convert.ToInt32(dat[0]));

    The output is: 49

    I thought the output need to be 1 and not 49,

    To see why you got 49, consult the Help:

    "The ToInt32(Char) method returns a 32-bit signed integer that represents 
    the UTF-16 encoded code unit of the value argument."

    Convert.ToInt32 Method (Char)
    https://msdn.microsoft.com/en-us/library/ww9t2871(v=vs.110).aspx

    - Wayne

    • Marked as answer by captain4gamer Tuesday, August 14, 2018 4:08 PM
    Tuesday, August 14, 2018 3:43 PM

All replies

  • Try this:

    string dat = "115";
    //Console.WriteLine(Convert.ToInt32(dat[0]));
    Console.WriteLine(Convert.ToInt32(dat[0].ToString()));
    

    - Wayne

    • Marked as answer by captain4gamer Tuesday, August 14, 2018 3:56 PM
    Tuesday, August 14, 2018 3:37 PM

  • string dat = "115";
    Console.WriteLine(Convert.ToInt32(dat[0]));

    The output is: 49

    I thought the output need to be 1 and not 49,

    To see why you got 49, consult the Help:

    "The ToInt32(Char) method returns a 32-bit signed integer that represents 
    the UTF-16 encoded code unit of the value argument."

    Convert.ToInt32 Method (Char)
    https://msdn.microsoft.com/en-us/library/ww9t2871(v=vs.110).aspx

    - Wayne

    • Marked as answer by captain4gamer Tuesday, August 14, 2018 4:08 PM
    Tuesday, August 14, 2018 3:43 PM
  • thank you very much!!! I didnt know what is the ToString() even doing, I looked and understood:

    "Converts the value of this instance to its equivalent string representation".

    Tuesday, August 14, 2018 3:59 PM
  • It returns the UTF-16 symbol in Integers and not Converts.

    1 is the 49th symbol in the first row of the UTF-16/

     
    Tuesday, August 14, 2018 4:10 PM