user3259793
user3259793

Reputation: 1

debugging integer to binary code? doesnt convert 32, 64

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

Answers (1)

waTeim
waTeim

Reputation: 9235

Here's another approach, some important details

  • Uses only int; using doubles is unnecessary and a source of possible error
  • Loop size based on sizeof.
  • Makes use of 0 == false, everything else == true. Simply masking the bit in question avoids the need to worry about the implementation specific behavior of right-shifting a signed value with the highest order bit set.
  • Doesn't use goto. Yea, goto is in the language, but only YACC can get away with it, people should not use it.

Source

#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

Related Questions