Decimal to Binary conversion

I am writing a program to covert decimal to binary. This is what I have soo far...


#include <iostream.h>
#include <conio.h>


void main(void)
{
int i, ch;
cout<<"Enter an integer: ";
cin>>ch;
for(i=0x80;i;i=i>>1)
cout<<((ch&i)?'1':'0');

getch();

char c1;
cin>>c1;

}


I need the program to list each digit of the output binary number on its own line. So for 128, I need the out put to show
7digit-1
6digit-0
5digit-0
4digit-0
3digit-0
2digit-0
1digit-0
0digit-0

Can anyone help me out? Thanks for any info
Well, there's (at least) two things you can do:
a) You can extract the bits from the big end, or
b) you can store the bits in an array/a vector, and then traverse it backwards.

For a), you'll need an unsigned int (which I'll call ander) with the value LONG_MIN (defined in climits); and [the size of int in bits] - 1 (sizeof(int)*8-1) (from now on, bits_in_int).
To get the first most significant bit, you bitwise-AND your number (n) and ander (don't overwrite n). Then right shift this number by bits_in_int bits, and the result is the most significant bit.
unsigned int bit=(((unsigned int)n))&ander)>>bits_in_int;

b) is the same thing you're doing, but instead of printing the bits, you're putting them in an array.

I like a) better. You use whichever you prefer.
(The size of my description is not indicative of the time it'll take you to write either of them.)
Last edited on
Here is a function that works
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int convert(int n)
{int k=1;
 while(k<n)//find the most significant bit
  k*=2;
 if(k>n)//fix the overshoot
  k/=2;

 while(k>0)
 {
 if(int(n/k)%2==0)cout<<0;//find the (next) most 
 else cout<<1;//significant binary digit
 k/=2;//go to the next column to the right and repeat
 }
}
hey buff bill, I am trying to use you function and it inst working for me. Should I change my integers from I and CH to K and N?? How should my final COUT statement look ? Thanks for your help
You should be able to just call the function with the integer you want to convert. It doesn't matter what you name your variables external to the function.

Be advised that the above implementation should generate a compile warning since it is declared to return an int but doesn't actually return anything.

Also, the code in the function could be shortened by more than 50%.
Topic archived. No new replies allowed.