Jump to content

Using stacks to convert from decimal to binary

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
J-Camz

J-Camz

    Newbie

  • Members
  • PipPip
  • 20 posts
I'm reviewing fro my exams and on a multiple choice paper that I did my teacher commented that stacks would be the best data structure to use when converting a decimal to binary. Can someone please explain why this is so?

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
It depends somewhat on your algorithm, but in general you are using repeated modulus and integer division by 2. You store the modulus on the stack, where the first stored value is the 1's place, second is 2's, third is 4's, etc. Then you can pop the stack to display the digits in standard order.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
J-Camz

J-Camz

    Newbie

  • Members
  • PipPip
  • 20 posts
I see
Thank you!
I really appreciate the quick reply. :)

#4
Aereshaa

Aereshaa

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 790 posts
That seems overly complicated. I would just put in all 32 binary digits in reverse order.
Watches: Nanoha, Haruhi, AzuDai. Listens to: E-Type, Dj Melodie, Nightcore.
"When people are wrong they need to be corrected. And then when they can't accept it, an argument ensues." - MeTh0Dz

#5
awazdohamko2004@gmail.com

awazdohamko2004@gmail.com

    Newbie

  • Members
  • PipPip
  • 25 posts
Common stack are not that powerful .. use dynamic data structure . try coding the same program with link-list .. its will seem to be difficult but you will have greater control over the program

#6
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
I won't comment on your post awazdo...


#include <stack>

#include <iostream>


int MyNumber = 495;

int base     = 2;


int main(void){

    std::stack<int> stack;

    while(MyNumber != 0){

        int remainder = MyNumber%base;

        int quotient  = MyNumber/base;

        stack.push(remainder);

        MyNumber = quotient;

    }

    while(!stack.empty()){

        std::cout << stack.top();

        stack.pop();

    }

    return 0;

}