0

Here's the work I've done so far:

2^32 = 10...0

subtract 1 -> 01...1 That gives you 32 1's

1 = 01

flip bits -> 11....10 add 1-> 1...1 That gives you 32 1's

Am I missing something? I'm asking because I tried a practice problem where you had to flip all the binary bits of a number. XOR'ing with -1 didn't work, but XOR'ing with 2^32 - 1 did.

3 Answers3

1

To create a any number in 2's complement form you flip the bits and add 1.

So for -1 it is the following

1 = 00000000000000000000000000000001
flip those bits
       11111111111111111111111111111110
add 1 to it and you get
       11111111111111111111111111111111

Now why is that -1?

Well -1 + 1 = 0.

if you add the following together you get

       11111111111111111111111111111111
      +00000000000000000000000000000001

you keep doing a bit carry to the next position on the left, ultimately overflowing the field and you have 0 remaining.

       00000000000000000000000000000000
WJS
  • 36,363
  • 4
  • 24
  • 39
0

A 32 bit 2's complement number can only represent values in the (inclusive) range -(2^31)..(2^31)-1. Since 2^32-1 is not in that range, it stands to reason whatever bit pattern you come up for it with actually corresponds to a value that does.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Let's number the 32 digits of an int, from 0 to 31. Digit #0 represents 2⁰, digit #1 represents 2¹, etc. More generally, digit #n represents 2ⁿ.

But we only have digits up to #31: we have 32 digits, but we started counting at 0. There is no 32nd digit to create 2³².

So what does the computer do? It basically pretends you wrote 2³² but then drops all but the first 32 digits (digits 0-31). This is called integer overflow. That means that 2³², which "should" be 1 followed by 32 0s, is actually just 32 0s -- which, of course, equals 0. Subtract 1 from that, and you get -1.

If you're working with longs (not ints), then you have 64 bits to work with instead of 32. In that case, overflow doesn't happen at bit 32, and you'll find that 2³² - 1 doesn't equal -1: it equals 4294967295, just like you'd expect. But in that case, 2⁶⁴ is 0 for similar reasons.

yshavit
  • 42,327
  • 7
  • 87
  • 124
  • I appreciate all the responses but this is perfect, thank you! Is there a reason why just using -1 as I tried wouldn't work with a long? –  Dec 20 '19 at 03:43
  • @khajiit Sorry, I don't understand the question. Could you show what you mean in terms of code? – yshavit Dec 20 '19 at 04:55
  • Nevermind, re-read your response and it was cleared up, thanks –  Jan 04 '20 at 00:54