I have byte to binary string function,
std::string byte_to_binary(unsigned char byte)
{
int x = 128;
std::ostringstream oss;
oss << ((byte & 255) != 0);
for (int i = 0; i < 7; i++, x/=2)
oss << ((byte & x) != 0);
return oss.str();
}
How can i write an int to bits in same way? I don't want extra 0's at the beginning of binary string so that is why i can't figure out how to create a variable length each time. Also, i'm not using std::bitset.
I'll just post this as an answer. It is shorter, safer and, what's most important, it is done.
Output:
Changed function name, though I'm not happy with that one... anyone got a nice idea?
You can do it using std:bitset and convert any number into bit string of any size, for example 64
Something like this should work (though I hacked it up quickly and haven't tested):
Since you mentioned your wish for C style in the comments, you might consider using itoa (or _itoa) if you are not worried about ANSI-C standard. Many compilers support it in stdlib.h. It also strips the leading 0's: