jasminwu / 1521-notes

Notes for COMP1521 - Computer Systems Fundamentals from when I took the course in 23T2.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Twos complement

scorpiontornado opened this issue · comments

Your example, converting -5 to two's complement, is slightly wrong - you had it as 011. This immediately jumps out as incorrect because negative numbers should have a leading 1 bit.

To see why, consider that two's complement can only store values in the range [−2^(N−1), 2^(N−1) − 1]. This means a 3 bit value can store numbers in the range [-4, 3]; -5 is outside this range. We must use 4 (or more) bits instead to store this value. Using the invert unsigned and add 1 rule, we get -5 -> 5 -> 0101 -> 1010 -> 1011, which is the representation of -5 in a two's complement machine.

Another way to understand two's complement is we want a value "c" such that
u + c = 2^n,
where u is the unsigned representation of the value we want to convert and c is the two's complement of u.

Rearranging, we can convert to two's complement the long way using:
c = 2^n - u,
e.g. for the signed value -5, we have N=4 bits, 2^N = 16, u = 5, c = 16 - 5 = 11 = 0b1011, the same result as earlier.

We can also convert back from a two's complement value to a regular (signed) value, s:
s = c - 2^N,
where s = -u. Using the previous example, we had the two's complement representation c = 0b1011 = 11. Thus, s = 11 - 2^4 = -5.

You might notice that 2^N doesn't fit into an N-bit integer, which is why we use the invert and add 1 method. Check out "Why Inversion and Adding One Works" here: https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html
In short, we're basically doing (2^N - 1) - u + 1 = (bitmask of N-1 ones) - u + 1 = ~u + 1

Thanks - fixed now