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

Asked

Viewed 91 times

3

I’m having a problem trying to add numbers that are in a variable, because it’s taking the ASCII Code from the same.

How do I directly pick the number that is within 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 on Ideone.

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

2 answers

4

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

Therefore, to obtain the numerical value of the digit having the character, simply subtract '0' his:

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

But usually you use another expedient 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 the Math.Pow(), which is much more expensive than an entire multiplication.

2


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

int j=int.Parse(bin[i].ToString());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.