0

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?

5
  • 5
    Welcome to Stack Overflow! Can you show us what you've tried so far? Commented Oct 23, 2017 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. Commented Oct 23, 2017 at 22:20
  • Search a little harder, this has been asked, and answered, at least half a dozen times just counting StackOverflow. Commented Oct 23, 2017 at 22:20
  • See stackoverflow.com/questions/111928/… Commented Oct 23, 2017 at 22:21
  • I ended up using a while loop instead, thanks while(val!=0) { s = (val%2==0 ? "0":"1") + s; val/=2;} Commented Oct 24, 2017 at 1:22

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

You might want to indicate whether this is Most Significant Bit first or Least Significant Bit first.
Thanks for the reply, I ended up using a while loop!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.