Converting Decimal to Binary...how to reverse?

Hi, so I have been trying for hours to figure out what to do to make this program work, but I am just not getting it. My assignment is to convert decimal to binary, octal, and hex. So far, I am still on binary because I have been hitting a problem. When I go to print the binary out, it's backwards. I cannot figure out how to reverse it. Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;
#include "stack.h"

int main()
{
    int num, total = 0;
    cout << "Please enter a decimal: ";
    cin >> num;
    while(num > 0)
    {
        total = num % 2;
        num /= 2;
        cout << total;
    }
    cout << endl;
    return 0;
}


I tried using a reverse function, only to realize that the sequence of numbers is not being stored as a string or integer, and that I do not know how to do that. So, if anybody could help me understand how to do this, that would be helpful.

Also, my professor gave me this class, but I have no idea how to implement it, or if I even need to for the binary portion:

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
52
53
#include <iostream>
using namespace std;

const int STACK_SIZE = 100;

class stack
{
private:
    int count;			// number of items in the stack
    int data[STACK_SIZE];
public:
    stack();
    ~stack();
    void push(const int item);	// push an item on the stack
    int pop();			// pop item off the stack
    int getCount() const;			// return count
};

stack::stack()	// constructor
{
	count = 0;	// zero the stack
}

stack::~stack() {}	// default destructor

void stack::push(const int item)
{
	if (count < STACK_SIZE)
	{
		data[count] = item;
		++count;
	}
	else cout << "Overflow!\n";
}

int stack::pop()
{
	if (count >0)
	{
		--count;
		return (data[count]);
	}
	else
	{
		cout << "Underflow!\n";
		return 0;
	}
}

int stack::getCount() const
{
	return count;
}
The stack is exatly what you need for your backward problem. It's easy:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;
#include "stack.h"

int main()
{
    int num, total = 0;
    cout << "Please enter a decimal: ";
    cin >> num;
    stack s; // You need the stack;
    while(num > 0)
    {
        total = num % 2;
        num /= 2;
        s.push(total); // push 'total'(?) onto the stack
        //cout << total;
    }
    while(s.getCount() > 0) // Another loop to get the values from the stack / now in the correct order
    {
        cout << s.pop();
    }
    cout << endl;
    return 0;
}
Oh wow. I hadn't thought to use the getCount method at all. >_< Thank you very much. Anyways, I have run into another problem. I have changed my program so that now I have this:

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>
using namespace std;
#include "stack.h"

int main()
{
    int decimal, remainder, choice;
    stack s;
    cout << "Please enter a decimal: ";
    cin >> decimal;
    cout << "Convert the number from decimal into:\n0 – Binary\n1 – Octal\n2 – Hexadecimal\n";
    cin >> choice;
    switch (choice)
    {
        case 0:
            while (decimal > 0)
            {
                remainder = decimal % 2;
                decimal /= 2;
                s.push(remainder);
            }
            break;
        case 1:
            while (decimal > 0)
            {
                remainder = decimal % 8;
                decimal /= 8;
                s.push(remainder);
            }
            break;
        case 2:
            while (decimal > 0)
            {
                remainder = decimal % 16;
                decimal /= 16;
                if (remainder > 9)
                        cout << char('A'  + remainder - 10);
                else
                    cout << remainder;
                s.push(remainder);
            }
            break;
        default:
            cout << "Invalid.";
    }
    while (s.getCount() > 0)
    {
        cout << s.pop();
    }
    return 0;
}


Binary and octal are both working fine, but I can't get hexadecimal to work. It comes out in reverse as well. I presume the problem comes from the fact that push doesn't work for the char data type, but I don't know how to resolve the issue. I need guidance here, please.
closed account (zb0S216C)
Here's how I convert decimal to binary:

1
2
3
4
char Number(5);

for(int I(0); I < (sizeof(Number) * 8); ++I)
    std::cout << ((Number &(1 << I)) ? 1 : 0);

I'm not sure if it's cross-platform, though. With this code, though, you can determine if your CPU is big endian or little endian.

Wazzak
Your switch case for hex numbers should be just like the other cases, with no o/p.

Then modify the output loop so it knows that 10 -> a, 11 -> b, etc.

Andy

PS And factor your case statements out, too!!
sounds like GWC homework ~_~

Like andywestken said, here was how I implemented this as a function using switch cases :

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
//other code here
    while(hexStack.getSize() > 0)
    {
        //buffer being a previously declared int
        buffer = hexStack.pop();
       //if it buffer (last value popped) is greater then 9... enter the switch statement
       //to assign it a letter, else just display the number(since it won't need a letter 
       //representation
        if(buffer > 9)
        {
            switch(buffer)
            {
                case 10 : cout << "A"; break;
                case 11 : cout << "B"; break;
                case 12 : cout << "C"; break;
                case 13 : cout << "D"; break;
                case 14 : cout << "E"; break;
                default : cout << "F"; break;
            }
        }
        else
            cout << buffer;
    }
    cout << " in hexadecimal\n";
    cout << endl;
}
Last edited on
@georgewashere - I assume your switch mechanism is assuming that the number is guaranteed to be in the range 0 - 15, given you're using the switch's default case to handle 15 -> F. If you are making this assumption, I would prob tweak the code to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    while(hexStack.size() > 0)
    {
        buffer = hexStack.pop();

        switch(buffer)
        {
            case 10 : cout << "A"; break;
            case 11 : cout << "B"; break;
            case 12 : cout << "C"; break;
            case 13 : cout << "D"; break;
            case 14 : cout << "E"; break;
            case 15 : cout << "F"; break;
            default : cout << buffer;
        }
    }
    cout << " in hexadecimal\n";
    cout << endl;


But if you do want to protect against values outside the range 0-15, then you need either (a) handle 15 as a specific case and use the default for out of range, and also handle underflow in the else. Or (b) use my version and protect the switch in an if(0 <= buffer && buffer <=15) test.

A more compact, pretty standard form of the trusting version is:

1
2
3
4
5
6
7
8
9
    while(hexStack.size() > 0)
    {
        buffer = hexStack.pop();

        static const char hexDigits[] = "0123456789ABCDEF";
        cout << hexDigits[buffer];
    }
    cout << " in hexadecimal\n";
    cout << endl;


Which can be extended more easily (than the switch-based code) to handle, for example, base 36.

static const char base36Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

http://en.wikipedia.org/wiki/Base_36
Last edited on
Hey, thanks to everyone who helped out. I ended up cleaning it up pretty nicely, I think. Here is my final product:
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
52
53
#include<iostream>
using namespace std;
#include "stack.h"

int main()
{
    int decimal, remainder, choice, base, intBuffer;
    stack s;
    cout << "Please enter a decimal: ";
    cin >> decimal;
    cout << "Convert the number from decimal into:\n0 – Binary\n1 – Octal\n2 – Hexadecimal\n";
    cin >> choice;
    if(decimal == 0)
    {
        if(choice >= 0 && choice <= 2)
            cout << 0;
        else
            cout << "Invalid.";
    }
    if(decimal != 0)
    {
        switch(choice)
        {
            case 0:
                base = 2;
                break;
            case 1:
                base = 8;
                break;
            case 2:
                base = 16;
                break;
            default:
                cout << "Invalid.";
                return 0;
        }
    }
    while(decimal > 0)
    {
        remainder = decimal % base;
        decimal /= base;
        s.push(remainder);
    }
    while(s.getCount() > 0)
    {
        intBuffer = s.pop();
        if(choice == 2 && intBuffer > 9)
            cout << char('A'  + intBuffer - 10);
        else
            cout << intBuffer;
    }
    return 0;
}

If anyone can think of how to further clean it up, I would be glad to listen.

@georgewashere - This IS GWC homework! It's Rex! Finally found a good opportunity to ask for help here. :P
Topic archived. No new replies allowed.