Thread: int2bin()

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    56

    int2bin()

    This function returns a binary representation in string form, of a given integer.

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    string int2bin(int num)
    {
        string returnString;
        int pos=0;
        for(int x=0; x <= 15; x++)
        {
            pos = (pos == 0) ? 1 : pos + pos;
            returnString =  (num & pos) ? "1"+returnString : "0"+returnString;
        }
        return returnString;
    }
    
    
    int main()
    {
        cout<<int2bin(255);
        return 0;
    }
    It seems to work fine when compiled;;;
    I posted here in case you guys have any suggestions regarding better coding.

  2. #2
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    You could do this with pos, which is a little simpler. (And I would probably name it mask instead of pos). Notice that I'm also reducing the scope of pos by declaring it inside the loop.

    Code:
    for (int i=0; i<16; ++i)
    {
        int pos = 1<<i;
        ...
    }
    Another change you may want to consider is adding ones or zeros to the end of the string and then reversing it when you're done.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You don't need x. Do the for-loop over pos, from 1 to 1<<16 and instead of increment it, you shift the mask left by one each time.
    Prepending onto a string is not that efficient either, so I'd consider starting at 1<<15 and shifting right instead each time.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed