Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

represent negative number with 2' complement technique?

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?

like image 275
ipkiss Avatar asked Feb 07 '12 06:02

ipkiss


3 Answers

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
like image 177
Spencer Uresk Avatar answered Oct 14 '22 22:10

Spencer Uresk


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

like image 25
prajeesh kumar Avatar answered Oct 14 '22 23:10

prajeesh kumar


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).

like image 28
Ates Goral Avatar answered Oct 15 '22 00:10

Ates Goral