converting binary to decimal using cstring

I'm trying to convert a binary 16 digit to a decimal. I believe its an issue with the formula.

#include <iostream>
#include <cmath>
#include <cstring>
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 += (int(b[i]) - 48)*pow(2,i);
else if (b[i] == '0') ;
else cout << " you are not inputting a binary number! \n";
i++;
sum++;
}
cout << sum;
char c; cin >> c;
return 0;
} //end main
It is indeed. For one, binary numbers are read from right to left. You should also not be incrementing the sum at the bottom of the loop. if you used #include <string> instead of #include <cstring> , this would be easier. Also, I'm guessing you haven't learned bit operations yet, but pow ( 2, i ) can be written as ( 1 << i ) and you won't have to #include <cmath> .

Take a look at c++ strings ( http://www.cplusplus.com/reference/string/string/ ) and how to use code tags on this forum ( http://www.cplusplus.com/articles/jEywvCM9/ ).
Last edited on
yes i removed the sum increment and made some changes. I have not learned bit operates, most is a carry over from java, but i have not learned about (2 << i). i've used math pow, but its the string length that i'm having trouble with setting up to take string length and go down the binary digits.
this is an update but don't think its an improvement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cmath>
#include <cstring>
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) 
	   { //each element of b[] is initialized to (char)0 - NUL
              if (b[i] == '1') sum += 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 
The problem is that cin >> b; reads into the first x chars in the array, but the smallest number in binary would be on the right. So if you entered 1010, it would be stored in b as 1010000000000000, which is a lot bigger than it should be. One solution would be to set every character in b to something other than a 0 or a 1 before you read into b. This could be done in a for..loop. If you filled b with 2, 1010 would be stored in b as 1010222222222222. You could then read it from right to left, ignoring all the 2's.
You could also read from left to right, and divide the result by pow ( 2, [# of 2's] ).

ps: (2<<i) is wrong. It would be (1<<i). I was off by one.
Topic archived. No new replies allowed.