patternMajor
Signed and unsigned numbers
Viewed 0 times
signednumbersandunsigned
Problem
How would the ALU in a microprocessor differentiate between a signed number, -7 that is denoted by 1111 and an unsigned number 15, also denoted by 1111?
Solution
Short version: it doesn't know. There's no way to tell.
If
More often, though,
EDIT: As Ruslan and Daniel Schepler quite rightly point out in the comments, some operands still need separate signed and unsigned versions, even on a two's-complement machine. Addition, subtraction, multiplication, equality, and such all work fine without knowing if the numbers are signed or not. But division and any greater-than/less-than comparisons have to have separate versions.
EDIT EDIT: There are some other representations too, like one's-complement, but these are basically never used any more so you shouldn't have to worry about them.
If
1111 represents -7, then you have a sign-magnitude representation, where the first bit is the sign and the rest of the bits are the magnitude. In this case, arithmetic is somewhat complicated, since an unsigned add and a signed add use different logic. So you'd probably have a SADD and a UADD opcode, and if you choose the wrong one you get nonsensical results.More often, though,
1111 represents -1, in what's called a two's-complement representation. In this case, the ALU simply doesn't care if the numbers are signed or unsigned! For example, let's take the operation of 1110 + 0001. In signed arithmetic, this means "-2 + 1", and the result should be -1 (1111). In unsigned arithmetic, this means "14 + 1", and the result should be 15 (1111). So the ALU doesn't know whether you want a signed or an unsigned result, and it doesn't care. It just does the addition as if it were unsigned, and if you want to treat that as a signed integer afterward, that's up to you.EDIT: As Ruslan and Daniel Schepler quite rightly point out in the comments, some operands still need separate signed and unsigned versions, even on a two's-complement machine. Addition, subtraction, multiplication, equality, and such all work fine without knowing if the numbers are signed or not. But division and any greater-than/less-than comparisons have to have separate versions.
EDIT EDIT: There are some other representations too, like one's-complement, but these are basically never used any more so you shouldn't have to worry about them.
Context
StackExchange Computer Science Q#105398, answer score: 45
Revisions (0)
No revisions yet.