Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a computer know that a two's complement number is negative?

Tags:

binary

For example, 10000001 is -127 in Two's Complement, but it's also equal to 129. How do I or a computer know which number it's referring to?

like image 808
Ryan Oliver Lanham Avatar asked Mar 01 '18 07:03

Ryan Oliver Lanham


2 Answers

From your question, I deduce you already know you are dealing with a signed integer. So, your real question is: how do we convert a two's complement representation to a decimal number?


For demonstration purposes, I will be using 4-bit integers. A two's complement number system encodes positive and negative numbers in a binary number representation. The weight of each bit is a power of two, except for the most significant bit (leftmost bit), whose weight is the negative of the corresponding power of two.

Example: Let's convert these two's complement numbers: 1110,0111,1001.

1110= -23 + 22 + 21 + 0*20 = -2
0111= -23*0 + 22 + 21 + 20 = 7
1001= -23 + 0*22 + 0*21 + 20 = -7

Remark: The leftmost bit gives you the sign of the number. That's, if it's "0", then the number is positive; if not, then it's negative.

So, to come back to the example you gave: 10000001 = -27 + 0 + 0 + 0 + 0 + 0 + 0 + 1= -127 (and not 129)

So, how do you represent 129 in two's complement?

To represent 129 in two's complement, you need more than 8 bits, since an additional bit is needed for the computer to know the number is positive. Not clear? Let's assume we are in a 16-bit system, here is how -127 and 129 would be stored:
-127= 10000001
129= 00000000 10000001 (The leftmost bit being 0 implies the number is positive)

In case you still doubt whether or not 129 can be represented using 8 bits in two's complement: Recall that on an n-bit system, the values that can be represented in two's complement lie in the interval [-2n-1,2n-1-1].
Here, n=8 bits. Thus, the interval is [-128,127], which clearly shows that 129 is out of range.

Source: https://en.wikipedia.org/wiki/Two's_complement
like image 182
James Avatar answered Sep 17 '22 15:09

James


How do I or a computer know which number it's referring to?

It depends on whether the given number is signed or unsigned.

Signed

Signed values can be positive or negative. Computers use the first bit to indicate this. If the first bit is 1, the number is negative. If the first bit is 0, the number is positive. To determine the value of the number, the other 7 bits are used.

Hence for a signed 1000 0001, it will mean -1

Unsigned

Unsigned values will only be positive. Since there is no indication needed for whether the number is positive or negative, all 8 bits will be used to determine the value of the number.

For an unsigned 1000 0001, it will mean 129

like image 22
user3437460 Avatar answered Sep 18 '22 15:09

user3437460