How to make the code not catch the ASCII Code of a variable?

3

I'm having a problem trying to add numbers that are in a variable, because you're getting the ASCII code from them.

How do I get the number directly inside a variable?

string bin = "1001001";
string final = "";
for (int i = 0; i < bin.Length; i++)
{
    int j = bin[i];
    final += Math.Pow(j * 10, bin.Length - i);
}
Console.WriteLine(final);

See working at Ideone .

For example, let's say that i has the value 1 , the right one would be to get 0 bin[1] , multiply by 10, and raise to 6 power, which would give 0. But code is taking bin[1] and representing it 48, which would be the value of it in the ASCII Table.

    
asked by anonymous 23.06.2017 / 03:28

2 answers

2

You can do the conversion from char to string, so you can get the actual value and then convert to integer

int j=int.Parse(bin[i].ToString());
    
23.06.2017 / 04:10
4

ASCII has a characteristic that the digits are in order, starting with '0' and ending with '9' . Thus, the ASCII value of '0' is 0x30, '1' is 0x31, etc., up to '9' being 0x39.

Consequently, to get the numeric value of the digit having the character, just subtract '0' from it:

for (int i = 0; i < bin.Length; i ++) {
    int j = bin[i] - '0';
    final += Math.Pow(j * 10, bin.Length - i);
}

But usually another expedient is used to analyze sequences of digits and turn them into numbers:

for (int i = 0, final = 0; i < bin.Length; i ++) {
    int j = bin[i] - '0';
    final = final * 10 + j;
}

This avoids using Math.Pow() , which is much more expensive than an integer multiplication.

    
23.06.2017 / 03:55