I have to convert an integer (from 0 to 225) to an 8 char binary string, I have been trying to use bitset but I'm not having any luck. How can I intake an integer and convert it to an 8 char binary string?
2 Answers
This is pretty easy to do without bitset, just as an alternate solution:
std::string ucharToBitString(unsigned char x)
{
std::string s = "";
for(int i = 0; i < 8; i++)
{
s += (x & 128) ? "1" : "0" ;
x <<= 1;
}
return s;
}
Edit: As per the comment, this handles the most significant bit first.
2 Comments
Thomas Matthews
You might want to indicate whether this is Most Significant Bit first or Least Significant Bit first.
sam
Thanks for the reply, I ended up using a while loop!
'0'or'1'to the string depending on the value of the bit.