简体   繁体   中英

Why -1 is internally represented as all 1's

Why is -1 internally represented as all 1's in a 16 bit compiler? This was used to solve the following program:

main()
{
    printf("%x",-1<<4);
}

I didn't understand the solution to this question.Please help. Thank you :)

Signed integers are represented as "two's complement".

When a number is positive, you will have its representation in binary as you expect.

When it's negative, it is being representd as two's complement. The two's complement of k, where k has N bits, is 2^Nk. Since 2^N is a one bit followed by k-1 zeros, you have, for example,

k = -3

N = 4 (4 bits, 2^N=16)

then -3 is represented as

16 - 3 = 13 , which in binary is 1101 .

You can then see that -1 is represented as

16 - 1 = 15 , which in binary is 1111

So, if the internal representation is two's complement, the number -1 will always be represented as a sequence of ones.

The table below shows the representation of integers with 4 bits. Negatives are represented as two's complements.

REPR   N
----  --
0111   7
0110   6
0101   5
0100   4
0011   3
0010   2
0001   1
0000   0
1111  -1
1110  -2
1101  -3
1100  -4
1011  -5
1010  -6
1001  -7
1000  -8

If you were using one's complement, then you'd have three bits for the number and one for the sign, so the table would be

REPR   N
----  --
0111   7
0110   6
0101   5
0100   4
0011   3
0010   2
0001   1
0000   0
1000   0
1001  -1
1010  -2
1011  -3
1100  -4
1101  -5
1110  -6
1111  -7

Why do we use 2's complement? Well, see that with one's complement you have two representations for zero (and we don't, in 2's complement). Besides that, you can add numbers (negative or positive) in two's complement and the result will just be correct.

One disadvantage of using two's complement is that you cannot represent abs(INT_MIN) .

More about two's complement in the Wikipedia article

Signed binary numbers use what's called a Two's Complement. Check out the wikipedia page: http://en.wikipedia.org/wiki/Twos_complement If it helps, think of it as representing -65536 + x.

Two's complement representation of signed int x :

  • If the most significant bit of x is 0, then just take the the value represented by x "as is".

  • If the most significant bit of x is 1, then calculate the value represented by x as follows:

    • Flip all the bits
    • Add 1 to the result
    • Consider the result as negative

-1 is stored as all 1's because it is in Two's Complement notation.

Two's complement notation is used for a variety of reasons, some of which include:

  • No special logic needed when dealing with negative numbers
  • No wasted bits (positive 0 and negative 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM