0

I need to convert a negative int to binary string. I used two's complement. For example, my number is -1.

First, I change the negative number to positive 1. Then, convert to binary string is 0001. Next, I flip the string is 1110.

The problem is I don't know how to add 1 to the string to get 1111.

I already used bit set function as with 32 bits like

bitset<32>(input).to_string();

It turns out 1111 1111 1111 1111 1111 1111 1111 1111. I only need the last 4. I don't know how to take away the rest. I need 32 bits because my input can be a large number such as -300.

Please help me with this.

1 Answer 1

1

If you are perfectly able to take an int, flip the sign and then flip all the bits but you just need help with adding one, there's a simple solution!

Add 1 before flipping the bits. That's it!

Your number is -1? Add one, get 0. Flip the sign, still 0. Convert to binary string, 0000. Now flip the bits and you have 1111 = -1!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! I figured it out. But do you know how to only get four bits out of 32 bits?
@vnsoshi you can use substr() to splice the string. ie for you you'd do str = bitset<32>(...; cout << str.substr(str.size()-4, 4); (see it running here)

Your Answer

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