Reputation:
Let's assume we have the following binary numbers with their representation:
| bin | unsigned | signed |
|:---:|----------|----------|
| 110 | 6 | -2 |
| 111 | 7 | -1 |
Now regardless if signed or unsigned, 111 + 110 = 1101
,
Now I can interpret the result 1101
as signed or unsigned which is:
| bin | unsigned | signed |
|:----:|----------|----------|
| 1101 | 13 | -3 |
Which matches the decimal operation:
6+7 = 13
-1-2 = -3
There was no difference between doing a signed addition
or unsigned addition
. So why would CPUs have different circuits/instructions for such operation?
Upvotes: 0
Views: 1089
Reputation:
It depends on the binary representation. This is a major point of 2s-complement representation -- when using 2s complement, signed and unsigned addition, subtraction, and mulitplication of fixed-width operands and same width results are identical, so you can use the same hardware instructions for both.
If you use 1s complement or sign magnitude, you need slight differences between signed and unsigned operations.
Division is different here, as are widening operations.
Upvotes: 2
Reputation: 365961
Because 2's complement add/sub is the same binary operation as unsigned add/sub. But for comparison (and division and widening multiply), interpretation of the MSB as a sign bit or not matters.
Some CPUs just have a cmp
instruction that sets all flags, and then you get your branch instruction checks a specific flag condition (predicate). Other CPUs without flags / condition codes (like MIPS and RISC-V) need predicates in their compare-into-register instructions.
SIMD compare instructions on x86 / ARM are also compare-into-register, not setting multiple different flags, so they also have the predicate as part of the compare instruction (like cmpps
takes an immediate byte with the predicate, or for integer there's pcmpgtd
/ pcmpeqd
.)
Upvotes: 2