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–>补码

20200304172430.png
20200304171926.png
20200304171945.png
20200304172228.png

Expanding

  • Unsigned: add zeros
  • Signed: sign extension:convert w-bit signed int x to w+k-bit int with same value

20200304172756.png

Overflow

Add

20200304210656.png

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

20200304211256.png

i will go around and become larger than cnt.
It works even if cnt is signed and <0

Integer Puzzles

InkedInkedCPuzzles_LI.jpg

  • overflow in + and *
  • TMin (TMin取反后还是自己,因为只有它不对称)
  • transformation between signed and unsigned

Shift

20200304213943.png

  • logical shift: Fill with 0 on left
  • arithmetic shift: Replicate most significant bit on left

Division for signed number

20200304214543.png
20200304214627.png

红色是符号位和arithmetic shift
黄色是数字位

+2^k-1可能会让数字位+1,这样商也会+1