Chapter2:计算机的算术运算
1.1 Signed Number Formats
for interger, we have:
- Sign and Magnitude:
use the leftmost bit to indicate the sign (0 for positive, 1 for negative). The remaining bits represent the magnitude. e.g.(101)-> -(01) = -1
- 1's Complement:
flip all the bits of the number, except the sign bit. e.g.(101)-> -(010) = -2
- 2's Complement:
flip all the bits of the number, except the sign bit, and add 1. e.g.(101)-> -(011) = -3
- Biased Notation:
Why we need Biased Notation:
We can see the binary representation on the left, if we think of it as unsigned numbers, they're arranged from smallest to largest; But the corresponding decimal integer on the right is piecewise single-increment. We want to have a representation such that the corresponding value on the right side also increases monotonically, and here we are.
IEEE 754: [ X ]b = X + 2n - 1
2 Arithmetic
2.1 Addition and Subtraction
For addition, we just simply add the two numbers.
For subtraction, there is a small difference. We can use the 2's complement to represent the negative number, and then add it to the positive number.
Overflow
Overflow Detection: Cn⊕Cn-1
note: sltu and sltiu for unsigned comparison
Logical operations
logical shift left (SLL) and logical shift right (SRL)
The machine instruction for the instruction: <--filled with 0!
e.g. slli x10, x9, 3
x9 111111111111111111 x10 111111111111111000
Also we have "and" as well as "or", but they are easy to understand.
and x11, x9, x10
or x11, x9, x10
Adder
Half adder : No carry handling Full adder : Carry handling
2.2 Multiplication
2.2.1 Unsigned Multiplication
Multiplicand (被乘数) × Multiplier (乘数)
For unsigned numbers, we simply multiply the two numbers.
For current bit, if the multiplier is 1, we add the multiplicand to the current bit. If the multiplier is 0, we do nothing.Then we shift the multiplicand to the left by 1 bit. But there is a problem .In this process ,we need 128+128+64 bit's register and a 128 bit ALU.This is too large and slow!
Note
do not shift the multiplicaned, instead (left) shift the product as well as (right) shift the multiplier。 ALU reduced to 64 bits。
2.2.2 Signed Multiplication
We should not use the same method directly.Instead, use the sign bit to ensure whether the number is positive or negative.