3.8 Notes
3.2-3.8 Learning Notes
CSAPP
int compare with unsigned int
If there is a mix of unsigned and signed in single expression,
signed values implicitly cast to unsigned
2’s Complement–>补码
Expanding
- Unsigned: add zeros
- Signed: sign extension:convert w-bit signed int x to w+k-bit int with same value
Overflow
Add
Multiplication
Use shift to replace multiply because it’s much faster
u<<3==u*8
(u<<5)-(u<<3)==u*24
How to use the unsigned
i
will go around and become larger than cnt.
It works even if cnt is signed and <0
Integer Puzzles
- overflow in + and *
- TMin (TMin取反后还是自己,因为只有它不对称)
- transformation between signed and unsigned
Shift
- logical shift: Fill with 0 on left
- arithmetic shift: Replicate most significant bit on left
Division for signed number
红色是符号位和arithmetic shift
黄色是数字位
+2^k-1
可能会让数字位+1
,这样商也会+1