# Thread: Help with C++ Math

1. ## Help with C++ Math

Hello, I am new to these great forums here and new to C++ too

Anyway, I am coding a binary to decimal converter and I have the math right and everything but C++ does not want to play nice with the math.

here is the output:
Code:
```  Enter a binary number: 11110000

1 = 98
1 =  (2 ^ 0) * 1
1 = 147
1 =  (2 ^ 1) * 1
1 = 0
1 =  (2 ^ 2) * 1
1 = 49
1 =  (2 ^ 3) * 1
0 = 288
0 =  (2 ^ 4) * 0
0 = 336
0 =  (2 ^ 5) * 0
0 = 192
0 =  (2 ^ 6) * 0
0 = 240
0 =  (2 ^ 7) * 0```
the decimal number shows the output C++ gave for the digit, the tabbed line under it shows the math it did to get that number, if you do the math manually the output should be different.

Here is my code:
Code:
```char inText[32];
int final;

cout << "\n  Enter a binary number: ";
cin >> inText;
cout << "\n  Decimal Result: \n";

for(int length = 0; length < strlen(inText); length++)
{
// The forumla
final += 2 ^ length * inText[length];

// Shows 1 = \$output
cout << inText[length] << " = " << ((2 ^ length) * inText[length]) << "\n\t";
// Shows 1 = (2 ^ \$len) * \$digit
cout << inText[length] << " = " << " (2 ^ " << length << ") * " << inText[length] << "\n";
}

cout << final;
cout << "\n\n";```

2. ^ is exclusive-or (a bit operator) in C and C++

If you want a 2 to the power of n, then do
(1<<n)

3. Thanks, now I get:
Code:
```1 = 98
1 =  (2 << 0) * 1
1 = 196
1 =  (2 << 1) * 1
1 = 392
1 =  (2 << 2) * 1
1 = 784
1 =  (2 << 3) * 1
0 = 1536
0 =  (2 << 4) * 0
0 = 3072
0 =  (2 << 5) * 0
0 = 6144
0 =  (2 << 6) * 0
0 = 12288
0 =  (2 << 7) * 0```
With:
Code:
```final += (2<<length) * inText[length];

cout << inText[length] << " = " << ((2<<length) * inText[length]) << "\n\t";
cout << inText[length] << " = " << " (2 << " << length << ") * " << inText[length] << "\n";```

4. 1. I said ONE, NOT TWO
1<<n
you did
2<<n

2. If you type in 11110000 then the left-most bit is bit 7, not bit 0
Code:
```for ( i = 0, b = 7 ; i < strlen(text) ; i++, b-- ) {
if ( ...   1<<b  ...
}```
3. When you do this
((2<<length) * inText[length])
You're not multiplying by 0 or 1, you're multiplying by '0' or '1' (which in the ASCII character set is 48 and 49 respectively)

So prior to maths, do this
Code:
`int int_value_of_bit = inText[length] - '0';  // convert '0','1' into 0,1`

5. Thank you, that solved my problems

Popular pages Recent additions