heyyo
heyyo

Reputation: 139

Understanding two's complement

I don't understand why an n-bit 2C system number can be extended to an (n+1)-bit 2C system number by making bit bn = bn−1, that is, extending to (n+1) bits by replicating the sign bit.

Upvotes: 1

Views: 114

Answers (1)

Greg
Greg

Reputation: 1500

This works because of the way we calculate the value of a binary integer.

Working right to left, the sum of each bit_i * 2 ^ i,
where 
    i is the range 0 to n
    n is the number of bits

Because each subsequent 0 bit will not increase the magnitude of the sum, it is the appropriate value to pad a smaller value into a wider bit field.

For example, using the number 5:

4 bit:     0101
5 bit:    00101
6 bit:   000101
7 bit   0000101
8 bit: 00000101

The opposite is true for negative numbers in a two's compliment system. Remember you calculate two's compliment by first calculating the one's compliment and then adding 1.

Invert the value from the previous example to get -5:

4 bit:     0101 (invert)->     1010 + 1 ->     1011
5 bit:    00101 (invert)->    11010 + 1 ->    11011
6 bit:   000101 (invert)->   111010 + 1 ->   111011
7 bit:  0000101 (invert)->  1111010 + 1 ->  1111011
8 bit: 00000101 (invert)-> 11111010 + 1 -> 11111011

Upvotes: 1

Related Questions