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.

Jive Dadson
  • 16,680
  • 9
  • 52
  • 65

1 Answers1

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!

scohe001
  • 15,110
  • 2
  • 31
  • 51
  • Thank you so much! I figured it out. But do you know how to only get four bits out of 32 bits? –  Jan 26 '18 at 00:26
  • @vnsoshi you can use [substr()](https://stackoverflow.com/questions/2477850/how-to-use-string-substr-function) to splice the string. ie for you you'd do `str = bitset<32>(...; cout << str.substr(str.size()-4, 4);` (see it running [here](https://ideone.com/F2eog5)) – scohe001 Jan 26 '18 at 00:57