Binary to decimal progam

Hello im writng a program that converts binary to decimals. i feel like im doing this all wrong considering its not working right.any help would be great!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

//this program converts Binary numbers to decimals
#include <iostream.h>

main()

{
      int a , b, c, d, e, f, g, dec;
   cout << "Enter a 7 bit binary value you wish to convert into decimal: " << '\n'; // asks user for binary
   cin >> a,b,c,d,e,f,g; 
   
g = g * 1;
cout << g;
f = f * 2;
e = e * 4;
d = d * 8;
c = c * 16;
b = b * 32;
a = a * 64;
dec = a + b + c + d + e + f + g;

cout << " Your decimal is:" << dec << '/n'; 
   
    system("pause");
   return 0;
}
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.13

[15.13] How can I "reopen" std::cin and std::cout in binary mode?

This is implementation dependent. Check with your compiler's documentation.

For example, suppose you want to do binary I/O using std::cin and std::cout.

Unfortunately there is no standard way to cause std::cin, std::cout, and/or std::cerr to be opened in binary mode. Closing the streams and attempting to reopen them in binary mode might have unexpected or undesirable results.

On systems where it makes a difference, the implementation might provide a way to make them binary streams, but you would have to check the implementation specifics to find out.
This shouldn't compile let alone work. You're taking input wrong, insert to each variable separately or parse the digits using division and modulus.
closed account (o1vk4iN6)
There would be a problem with "dec", since that is used by std, unless you aren't using the entire namespace it'll be fine.

You can even do something more like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

const int bits = 7;
int value = 0;

cout << "Enter a " << bits << " bit binary value: ";

for(int i = 1; i <= bits; i++)
{
    char c;
    cin >> c;
 
    if(c == '1')
         value |= 1 << (bits - i);
}

cout << "Decimal is: " << value << endl;


That'll only work for as long as "value" has enough memory to store all the bits, so up to 32 in this case.
Last edited on
Topic archived. No new replies allowed.