I want to square every digit in str
and concatenate it to pow
.
I have this simple code:
string str = "1234";
string pow = "";
foreach(char c in str)
{
pow = Math.Pow(Convert.ToInt32(c), 2);
}
It should return 14916
- instead it returns: 2401250026012704
But if I use int.Parse(c)
, it returns the correct number.
foreach(char c in str)
{
int i = int.Parse(c.ToString());
pow = Math.Pow(i, 2);
}
Why does Parse
work and Convert
doesn't?
CodePudding user response:
From the documentation of Convert.ToInt32(char)
:
The
ToInt32(Char)
method returns a 32-bit signed integer that represents the UTF-16 encoded code unit of the value argument.
Therefore, for example, the char '1'
will be converted to the integer value 49
, as defined in the UTF-16 encoding: https://asecuritysite.com/coding/asc2.
An alternative approach to the int.Parse(c.ToString())
example, would be Char.GetNumericValue
:
foreach(char c in str)
{
pow = Math.Pow(char.GetNumericValue(c), 2);
}
This converts the char to the numeric equivalent of that value.
CodePudding user response:
In the first code snippet, Convert.ToInt32(c)
is converting the character to its ASCII value, rather than its numerical value. Since the ASCII value of the character '1' is 49, the code is squaring 49 and adding it to the string.
On the other hand, int.Parse(c.ToString())
is converting the character to a string and then parsing that string to an integer. This results in the correct numerical value of 1 being squared and added to the string.