简体   繁体   中英

Convert negative int to binary string in c++

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM