0

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?

1
  • 1
    You can use Math.Pow(Char.GetNumericValue(c), 2). You should not compare apples with pears. Once you convert a char to int and then you parse a String to int. The rules are different. Commented Jan 16, 2023 at 8:37

1 Answer 1

8

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.

3
  • You can also do Math.Pow(Convert.ToInt32(c.ToString()), 2) Commented Jan 16, 2023 at 8:43
  • 1
    @Danial You could, but Char.GetNumericValue is more idiomatic than using an intermediate string. Commented Jan 16, 2023 at 8:50
  • int result = c - '0'; is faster
    – fubo
    Commented Jan 16, 2023 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.