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?
Asked
Active
Viewed 801 times
0
-
5Welcome to Stack Overflow! Can you show us what you've tried so far? – templatetypedef Oct 23 '17 at 22:17
-
Write a loop that gets each bit from the integer, and then adds the character `'0'` or `'1'` to the string depending on the value of the bit. – Barmar Oct 23 '17 at 22:20
-
Search a little harder, this has been asked, and answered, at least half a dozen times just counting StackOverflow. – Ben Voigt Oct 23 '17 at 22:20
-
See https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format – Barmar Oct 23 '17 at 22:21
-
I ended up using a while loop instead, thanks while(val!=0) { s = (val%2==0 ? "0":"1") + s; val/=2;} – sam Oct 24 '17 at 01:22
2 Answers
2
You are on a good way using bitset
, I think. Don't know which issues you had with bitset
, but try the following. Note that a bitset can be initialized with various types of values, one being integral type:
int main() {
int value = 201;
std::bitset<8> bs(value);
cout << bs.to_string();
}

Stephan Lechner
- 34,891
- 4
- 35
- 58
0
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.

Cody
- 2,643
- 2
- 10
- 24
-
You might want to indicate whether this is Most Significant Bit first or Least Significant Bit first. – Thomas Matthews Oct 23 '17 at 23:27
-