PDA

View Full Version : how to reverse the output in c++


sarah
1 Jul 2005, 9:15am
hi!
there is a c++ programe to convert a decimal number into binary.i have somehow done it but the output is in reverse order.that is if we take input 4 then the answers should be 100 but it gives 001.plz guide me what to do?

mmonnin
1 Jul 2005, 4:19pm
Again, code please.

shwaip
1 Jul 2005, 4:22pm
if the input is an int:

void printInt(int toPrint){
int x = 0x8000;
for(int i=0; i<32; i++){
if( (x & toPrint) == 0)
cout << "0";
else
cout << "1";
x = x >> 1;
}
}


This masks off all the individual bits, and tests if' the result is zero. If it is, that bit is a zero.

sarah
1 Jul 2005, 5:35pm
Again, code please.
<
main()
{
int n,r;
cout<<"enter the integer";
cin>>n;
while(n>=1)
{
r = n % 2;
n = n/2;
cout<<r;
}
}
>
this is the code,with which i have tried to solve the problem but...

cswett
1 Jul 2005, 5:44pm
if the input is an int:

void printInt(int toPrint){
int x = 0x8000;
for(int i=0; i<32; i++){
if( (x & toPrint) == 0)
cout << "0";
else
cout << "1";
x = x >> 1;
}
}


This masks off all the individual bits, and tests if' the result is zero. If it is, that bit is a zero.

Be carefull of the big-endian/little-endian difference on machines. You might get;

000000000000001000000000000000000

when you want

00000000000000000000000000000100

shwaip
1 Jul 2005, 5:56pm
cswett - yeah, there are a couple problems with the code I posted, including little/big endian assumptions and and size of int assumptions.

sarah - The only way I can think of to solve the code using the way that you're working on it is to store the values in a temporary string, and then print it after you're done.

sarah
1 Jul 2005, 5:56pm
Again, code please.
<
main()
{
int n,r;
cout<<"enter the integer";
cin>>n;
while(n>=1)
{
r = n % 2;
n = n/2;
cout<<"r;
}
}
>

shwaip
1 Jul 2005, 6:03pm
if you put the code in code here tags, it'll keep your indents.