wrong output

closed account (4w7X92yv)
Hello

I wrote a program that converts a binary value to a dec number
But it converts wrong:

input : 1111100
output:31

but 31 decimal is 0011111 binary
1111100 binary is 124 decimal

what do i do wrong?

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

#include <iostream>
#include <cstdlib>
#include <string>
#include <cmath>
using namespace std;
int main()
{
  string bin;
  double dec = 0;
  
  cin >> bin;
  
  for(int counter = 0; counter < bin.size(); counter++)
    if(bin.c_str()[counter] == '1')
      dec += pow(2.0, (double)counter);

  cout << dec << endl;
  
  system ("pause");
  return 0;
}
Numbers in any base are read from right to left, so why do you read left to right?
closed account (4w7X92yv)
If the user inputs 1111100 it outputs 31 while it should be 124
If the user inputs 0011111 it outputs 124 while that should be 31

Idk what i do wrong but its something
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstdlib>
#include <string>
#include <cmath>

using namespace std;

int main()
{
  string bin;
  // double dec = 0; // decimal or "floating point" number are in IEEE representation this won't work unless the binary string is the full 64 bits and appropriately constructed
  long long dec = 0; // could use char, short, int, etc depending on the size of the string entered

  cin >> bin;

  for(int counter = 0; counter < bin.size(); counter++)
    if(bin.at(counter) == '1') // don't know why you'd output a const cstring before taking the index? this is preferred.
    {
      dec += pow(2.0,double(bin.size() - 1 - counter)); // we're starting on the left-hand (most significant) side of the string
    }
  cout << dec << endl; // this will always be calculated as unsigned
  return 0;
}
Last edited on
std::bitset already does this too:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <bitset>
#include <iostream>
#include <string>

int main()
{
  std::string bin;
  std::getline(std::cin,bin);
  std::bitset<64> bs_ulong(bin);
  std::cout << bs_ulong.to_ulong() << std::endl;
  return 0;
}
closed account (4w7X92yv)
thanks :)
Topic archived. No new replies allowed.