CSAPP大实验期末作业
在给出的readme中,它提供了一些工具和方法。例如
![这是dlc 工具,用来检查bits.c文件中各个函数是否有违法的符号。](https://img-blog.csdnimg.cn/20190527212433936.png)
这是dlc 工具,用来检查bits.c文件中各个函数是否有违法的符号。
还可使用btest来测试bits.c 的正确通过样例数,每次测试都需要使用make编译。
可以单独测试某一个函数是否正确
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190527212828823.png)
或者全部的函数:
![在这里插入图片描述](https://img-blog.csdnimg.cn/2019052721293430.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0OTA1MzA2,size_16,color_FFFFFF,t_70)
endif
bitAnd - x&y using only ~ and |
- Example: bitAnd(6, 5) = 4
- Legal ops: ~ |
- Max ops: 8
- Rating: 1
int bitAnd(int x, int y) {
int ret = ~(~x | ~y);
return ret;
}
getByte
getByte - Extract byte n from word x
- Bytes numbered from 0 (LSB) to 3 (MSB)
- Examples: getByte(0x12345678,1) = 0x56
- Legal ops: ! ~ & ^ | + << >>
- Max ops: 6
- Rating: 2
int getByte(int x, int n) {
int tmp = ((x << ((4 + (~n)) << 3)) >> 24);
return tmp&0x000000ff;
}
思路是得到Byte后,先左移使有效位到最左边,再右移24位到最右边,这样就使得前面置0.将其移动到最左边的位数可通过n计算,但因为不可以使用减号,通过使(3 - n = 3 + ~n + 1) << 3的到左移的位数。
logicalShift
logicalShift - shift x to the right by n, using a logical shift
- Can assume that 0 <= n <= 31
- Examples: logicalShift(0x87654321,4) = 0x08765432
- Legal ops: ! ~ & ^ | + << >>
- Max ops: 20
- Rating: 3
int logicalShift(int x, int n) {
int ret = (x >> n) & (~(((1<<31)>>n)<<1));
return ret;
}
思路是逻辑右移补零,当负数时,消去前面的1,特殊情况时当n = 0的时候需要特别注意。
bitCount
bitCount - returns count of number of 1’s in word
- Examples: bitCount(5) = 2, bitCount(7) = 3
- Legal ops: ! ~ & ^ | + << >>
- Max ops: 40
- Rating: 4
int bitCount(int x) { // 用二分法,从小到大依次获取2、4、8、16、32个01位中1的个数。
int bitcount;
int tmp1 = (0x55)|(0x55<<8);
int mask1 = (tmp1)|(tmp1<<16); //得到01010101……01010101
int tmp2 = (0x33)|(0x33<<8);
int mask2 = (tmp2)|(tmp2<<16); //得到00110011……00110011
int tmp3 = (0x0f)|(0