-1

Run the following in python3

>>> print(2, bin(2), ~2, bin(~2))
> 2 0b10 -3 -0b11

I thought ~2 should be 0b01 or 0b101.

Why -0b11?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Xin
  • 737
  • 3
  • 10
  • 27

2 Answers2

2
 2  = 00000010
~2  = 11111101

What's the value of 11111101 in two's complement?

To answer that, follow this simple algorithm:

  • Flip all bits
  • Add 1 to the result
  • Determine the sign according to the MSB

11111101 > 00000010 > 00000011 
         ^          ^ 
       Flip       Add 1

Note that the most significant bit is "1", so the sign is negative.

Maroun
  • 94,125
  • 30
  • 188
  • 241
1

First lookat ~2:

 2 = 0b0000...10 (n leading 0s)
~2 = 0b1111...01 (n leading 1s)

Then analysis -0b11

most computer number representation using the two's complement notation, where:

A - B = A + ~B + 1

So -0b11 is acturally:

  - 0b11
= 0 - 0b11
= 0b0000...00 + 0b1111...00 + 1
= 0b1111...01
Zang MingJie
  • 5,164
  • 1
  • 14
  • 27