CSAPP 第二章随笔

时间:2024-01-13 19:11:14

类型转换问题

(1)int -> short 二进制位高位截断,低位保持不变

(2)同类型 unsign -> sign 记住二进制位是不变的

(3)P101页提到的编译器乘法优化问题,一般的乘法需要cpu时钟周期(i7 cpu下乘法也要3 clock cycles)比加法和位移、对二进制位的操作等(only 1 clock cycle)要慢很多。

所以一般乘法 如x*b,编译器会自动转换为若干个x*2^n然后相加的形式,然后只要执行位移和加法就可以完成乘法运算了,可以缩短所需要的时钟周期。注意溢出也没事照做。

对于一些常数K,表达式x*K,编译器可以将K的二进制表示为分开的若干个0或1的序列

[(0…0)(1…1)(0…0)…(1...1)]。

For example,14 can be written as [(0…0)(111)(0)].

Consider a run of ones from bit position n down to bit position m. (n >= m)

如1的起点二进制位posi 为1,终点为3

这样的话,x*K就可以表示为下列两种形式

Form A:(x << n) + (x <<(n-1)) + …+(x<<m)

Form B:(x << (n+1) – (x << m))

(4)P104除法优化问题,同理

Integer division on most machine is even slower than integer multiplication—requiring 30 or more clock cycles.

P116

注意这个Denormalized number.

P120

Floating point Rounding

There are four rouding mode(凑整模式):

Round-to-even, Round-toward-zero,Round-down,Round-up;

When using Round-to-mode, both 1.2350000 and 1.2450000 would be round to 1.24 since 4 is even(偶数的). As to binary fractional, it means that we prefer to have the least significant bit equal to zero.

P125

浮点数类型转换问题

From float or double to int:

The value will be round to zero. For example, 1.999 will be converted to 1, while -1.999 will be converted to -1.