9

I am using 2' complement to represent a negative number in binary form

Case 1:number -5

According to the 2' complement technique:

Convert 5 to the binary form:

00000101, then flip the bits

11111010, then add 1

00000001

=> result: 11111011

To make sure this is correct, I re-calculate to decimal:

-128 + 64 + 32 + 16 + 8 + 2 + 1 = -5

Case 2: number -240

The same steps are taken:

11110000

00001111

00000001

00010000 => recalculate this I got 16, not -240

I am misunderstanding something?

ipkiss
  • 13,311
  • 33
  • 88
  • 123

3 Answers3

12

The problem is that you are trying to represent 240 with only 8 bits. The range of an 8 bit signed number is -128 to 127.

If you instead represent it with 9 bits, you'll see you get the correct answer:

011110000 (240)

100001111 (flip the signs)
+
000000001 (1)

=

100010000

=

-256 + 16 = -240
MA Xilai
  • 3
  • 2
Spencer Uresk
  • 3,730
  • 26
  • 23
4

Did you forget that -240 cannot be represented with 8 bits when it is signed ?

prajeesh kumar
  • 1,916
  • 1
  • 17
  • 17
3

The lowest negative number you can express with 8 bits is -128, which is 10000000.

Using 2's complement:

128 = 10000000
(flip) = 01111111
(add 1) = 10000000

The lowest negative number you can express with N bits (with signed integers of course) is always - 2 ^ (N - 1).

Ates Goral
  • 137,716
  • 26
  • 137
  • 190