0
votes

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

1 Answers

1
votes

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!