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?
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.