Reputation: 941
Basically, Program Counter might have unsigned int value:
For example, if PC is 0b11110000(240)
, then we think that it's 240, not the negative value.
However, if we add offset(sign-extended) to above PC(0b11110000)
, the added value can be negative or positive:
For example, if we add 0b11111001(-7) to PC 0b11110000(240), the PC should have 233(which means we do add operation between unsigned and signed). However, if offset is positive value, then PC 0b11110000(240) + offset 0b00001111(15) = 255(which means we do add operation between unsigned and signed)
How add operation between unsigned and signed can be done?
Upvotes: 1
Views: 1334
Reputation: 47933
One of the nice things about two's complement arithmetic is that it works consistently for both signed and unsigned quantities. In fact, much of the time, the CPU doesn't know/care whether it's operating on signed or unsigned quantities -- up to a point (and especially for addition and subtraction), it's mostly a matter of interpretation.
You asked about 240 + -7 and 240 + 15. Let's look at both of those problems in both the signed and unsigned domains:
unsigned + signed:
240 + -7 = 233
240 + 15 = 255
unsigned + unsigned:
240 + 249 = 233 (489 % 256)
240 + 15 = 255
signed + signed:
-16 + -7 = -23
-16 + 15 = -1
signed + unsigned:
-16 + 249 = -23
-16 + 15 = -1
What's going on here? Well, 233 unsigned is the same as -23 signed: they're both 11101001 (in 8 bits). In binary the two problems look like this:
11110000 + 11111001 = (1)11101001
11110000 + 00001111 = 11111111
The first result overflows: It's really 111101001 (489), but it overflows and we lose the 9th bit, resulting in 11101001 (233).
The rest is all interpretation. 11110000
is -16 signed, or 240 unsigned. 11111001
is -17 signed, or 249 unsigned. 11101001
is -23 signed, or 233 unsigned. 11101111
is -1 signed, or 255 unsigned. And 00001111
is always 15.
(All of this assumes two's complement. Things would be rather different in one's complement, or sign/magnitude. But two's complement is what your computer uses.)
Upvotes: 2