Help with code for binary to decimal conversion!

My code compiles and runs but when you enter 10010001 it returns 137, and it SHOULD be 145! I dont know where the issue is occuring. Please help!

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
char b[16];
cout << "Please input a binary number up to 16 digits...\n\n";
cin >> b;
int sum = 0, i=0;
while (i<16 && b[i] != (char)0) {
if (b[i] == '1') sum += pow(2, i);
else if (b[i] == '0') ;
else cout << " you are not inputting a binary number! \n";
i++;
}
cout << sum;
char c; cin >> c;
return 0;
} //end main
AAAh - but it is 137 given the direction/orientation your calculation is using.

Very subtle - I'll leave you to figure it out ...
Last edited on
First of all I checked the value of the string you showed and indeed it is equals to 145. Here is the code that proves this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <numeric>

int main()
{
	std::string s( "10010001" );

	unsigned int x = std::accumulate( s.begin(), s.end(), 0u,
	                                  []( unsigned int s, char i )
	                                  {
							  return ( 2 * s + i - '0' );
	                                  } );

	std::cout << "x = " << x << std::endl;

	return 0;
}



As for your code I would write it the following way


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int sum = 0, i=0;

while ( i<16 && b[i] ) 
{ 
   if (b[i] == '1' || b[i] == '0' ) 
   {
      sum = 2 * sum + b[i] - '0'; 
   }
    else 
   {
      cout << " you are not inputting a binary number! \n";
      break;
   }
   i++;
}
Last edited on
Yes it is expected to be 145 - because
given the binary value 10010001 we treat the right most bit as the least significant bit and the leftmost bit as the most significant bit.
so 10010001 is expected to be 128+16+1 = 145.

BUT in his code, he is starting at b[0] which is the left most bit and treating that as the least significant bit - which gives the result.
1 + 8 + 128 = 137.

Which is why I made the hint about direction/orientation in my first post.

sheesh....

Last edited on
@guestgulkan


Why are you writing about this the second time? I understood what you say the first time and hope the PC also understood.:)
When I was writing my post I did not see yet your post.:) Our posts do not contradict each other.:)
Last edited on
my bad :-)
Last edited on
Topic archived. No new replies allowed.