Reputation: 1
So here is my problem, I have (what I think) is a decent section of code, it seems to work for most numbers I put in. However, when I put in a 2^x
number (32
or 64
for example) it returns 10
rather than 10000000
, which obviously isn't right. Any help would be greatly appreciated.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
//void thework(unsigned int num); /*was going to take this another direction and decided not to*/
int main(){
int num;
int por;
int mun;
por = 64;
cout<<"imput a number you want to convert to binary"<<endl;
cin>>num;
start:
if(num < pow(2.0,por)){ /*just to get the power widdled down to size*/
por--;
goto start;
}
/*part 2 is the "print 1" function, part 2 is the "print 0 and return to part 1, or kill section */
p2:
if((num >= (pow(2.0,por)))&&(num != 0)){
cout<<"1";
num -= pow(2,por);
por--;
goto p2;
}
p3:
if((num < pow(2,por))&&(num > (-1))){
mun=num;
if((mun -= pow(2.0,por)) > 0){
cout<<"1";
num -= pow(2.0,por);
goto p2;
}
if((mun -= pow(2.0,por)) > 0){
cout<<"0";
num -= pow(2.0,por);
por--;
goto p2;
}
return 0;
}
Upvotes: 0
Views: 51
Reputation: 9235
Here's another approach, some important details
#include <iostream>
using namespace std;
int main(int argc,char *argv[])
{
int num;
cout << "input a number you want to convert to binary" << endl;
cin >> num;
for(int j = sizeof(num)*8 - 1;j >= 0;j--)
{
if(num & (0x1 << j)) cout << "1";
else cout << "0";
}
cout << endl;
return 0;
}
Upvotes: 1