"to_decimal" function

Hello. Is there something wrong with my logic? The results are wrong and I can't find errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//the string is supposed to be binary code.
int to_decimal(string s)
{
	int sum = 0;
	int counter = 0;
	for (int i = 0; i<s.length(); i++)
	{
		if (s[i] =='1')
		{
			counter++;
		}
	}
	for (int i = 0; i < counter; i++)
	{
		sum += pow(2, i);
	}
	return sum;
}
Last edited on
read below
Last edited on
There are so many things wrong with the logic, you should start over and try another approach.

First of all, suppose I had the binary number 100, which is 4 in decimal. In your function, counter would become 1, in your loop,

sum += 2^0
sum += 2^1

which gives 3. The logic behind your second loop is obviously wrong.

Another example, suppose I had 110. That means counter becomes 2. But wait, what if I had 101? The counter also becomes 2. The logic behind your first loop is also wrong.
This must be better:
1
2
3
4
5
6
7
8
9
10
11
12
13
int to_decimal(string s)
{
	int sum = 0;
	reverse(s.begin(), s.end());
	for (int i = 0; i<s.length(); i++)
	{
		if (s[i] =='1')
		{
			sum += pow(2, i);
		}
	}
	return sum;
}
closed account (SECMoG1T)
Hi, you might be interested in this one here :
http://www.cplusplus.com/forum/beginner/158464/
@might asker
Good job. :)

Here's a function that converts from one base to another.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
#include <cmath>

std::string convertNumber(std::string in, unsigned int fromBase, unsigned int toBase)
{
    std::string out = "";
    std::string alnum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    unsigned long long value = 0;

    std::reverse(in.begin(), in.end());
    for (unsigned int i = 0; i < in.length(); ++i)
    {
        if (isalpha(in[i]))
            in[i] = toupper(in[i]);
        auto pos = alnum.find(in[i]);
        value += pow(fromBase, i) * pos;
    }

    while (value > 0)
    {
        auto pos = value % toBase;
        out = alnum[pos] + out;
        value /= toBase;
    }

    return out;
}

int main()
{
    std::string num;
    unsigned int from, to;
    
    std::cout << "To exit program, enter 0 as the number to convert.\n\n";
    std::cout << "Enter a number to convert: ";
    std::cin >> num;
    while (num != "0")
    {
        std::cout << "Base to convert from: ";
        std::cin >> from;
        std::cout << "Base to convert to: ";
        std::cin >> to;
        std::cout << "Converted number: " << convertNumber(num, from, to);
        std::cout << "\n\nEnter a number to convert: ";
        std::cin >> num;
    }
    return 0;
}


Obviously it doesn't work if one of the bases is larger than 36.
Topic archived. No new replies allowed.