-
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.
-
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.
-
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.