CSAPP大实验期末作业


在给出的readme中,它提供了一些工具和方法。例如
这是dlc 工具,用来检查bits.c文件中各个函数是否有违法的符号。
这是dlc 工具,用来检查bits.c文件中各个函数是否有违法的符号。
还可使用btest来测试bits.c 的正确通过样例数,每次测试都需要使用make编译。
可以单独测试某一个函数是否正确 在这里插入图片描述
或者全部的函数:
在这里插入图片描述

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
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值