View Full Version : how to reverse the output in c++
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.
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.
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...
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
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.
Again, code please.
<
main()
{
int n,r;
cout<<"enter the integer";
cin>>n;
while(n>=1)
{
r = n % 2;
n = n/2;
cout<<"r;
}
}
>
if you put the code in code here tags, it'll keep your indents.
vBulletin® v3.8.1, Copyright ©2000-2009, Jelsoft Enterprises Ltd.