Hi, I'm new here and this is my first post. I have been trying to learn some programming as a part time hobby. Is it possible for someone to help me write a simple program to convert any base through 10 to base 2 using stacks and arrays. I've been looking around for help and have not had much luck finding something understandable. Thank you
2 Replies  4191 Views  Last Post: 09 April 2007  08:36 AM
#1
Using stacks and arrays to convert any base to base 2
Posted 09 April 2007  06:17 AM
Replies To: Using stacks and arrays to convert any base to base 2
#2
Re: Using stacks and arrays to convert any base to base 2
Posted 09 April 2007  07:14 AM
well converison of bases is not all that difficult
say that Num is and int holding some number that we want to convert.
Of course this is NOT the only way to convert. I can think up three more just sitting here.
BTW. The % operator is something that you should get familier with. It is rather useful, though it is a bit tricky for some people. It gives the remainder of a division (5 % 2 = remainder of 5/2 = 1). It also gives the modulus of a number, so 8 mod 5 = 3 so 8 % 5 = 3.
so if we wanted to convert to another base we might use the code like:
say that Num is and int holding some number that we want to convert.
#include <iostream> using std::cout; int main() { int Num=12345; //number to convert. while (Num) { cout << (Num % 2); //Print the remainder of division Num / 2 Num /= 2; //Do the division } return 0; }The problem with this code is that it outputs the number backwards. That is the Lease significant bit(LSB) is to the far left, and the most significant bit is to the far right. So we can use a stack to reverse the order by pushing each bit onto the stack as we find them. Since a stack is a FILO (first in, last out) when we pop the digits off the stack they will be in the right order.
Of course this is NOT the only way to convert. I can think up three more just sitting here.
BTW. The % operator is something that you should get familier with. It is rather useful, though it is a bit tricky for some people. It gives the remainder of a division (5 % 2 = remainder of 5/2 = 1). It also gives the modulus of a number, so 8 mod 5 = 3 so 8 % 5 = 3.
so if we wanted to convert to another base we might use the code like:
#include <iostream> using std::cout; int main() { int Num=12345; //number to convert. int base = 5; while (Num) { cout << (Num % base); //Print the remainder of division Num / base Num /= base; //Do the division } return 0; }Which would give use the number base 5 (with the digits backwards of course).
#3
Re: Using stacks and arrays to convert any base to base 2
Posted 09 April 2007  08:36 AM
Thank you so much. I understand what you did. All i have to do now is push it into a stack to reverse the order to get the correct numbers.
Page 1 of 1
