CSAPP Lab1: 位操作实现基本运算

本文详细介绍了CSAPP实验中的15个位操作任务,包括pow2plus1、pow2plus4、bitXor等,每个任务都限制了可使用的操作符,并且禁止使用循环和条件语句,以及超过8位的常数。实验旨在通过位操作实现各种基本的算术和逻辑功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实验要求

给出15个函数,规定了实现每个函数需要的逻辑和算术操作符(规定数量)。
只能使用规定的操作符! ˜ & ˆ | + << >>
不能使用循环或者条件语句
不能使用超过8位的常数(ff)

实现代码

1、pow2plus1

/*
 * pow2plus1 - returns 2^x + 1, where 0 <= x <= 31
*/
int pow2plus1(int x) {
   
     /* exploit ability of shifts to compute powers of 2 */
     return (1 << x) + 1;
}

2、pow2plus4

/*
* pow2plus4 - returns 2^x + 4, where 0 <= x <= 31
*/
int pow2plus4(int x) {
   
	/* exploit ability of shifts to compute powers of 2 */
	int result = (1 << x);
	result += 4;
	return result;
}

3、bitXor

/*   bitXor - x^y using only ~ and & 
 *   Example: bitXor(4, 5) = 1
 *   Legal ops: ~ &
 *   Max ops: 14
 *   Rating: 1
 */
int bitXor(int x, int y) {
   
	return (~(x&y))&(~(~x&~y));//列出真值表
}

4、tmin

/*   tmin - return minimum two's complement integer 
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 4
 *   Rating: 1
 */
int tmin(void) {
   
	return 1<<31;//0x80000000
}

5、isTmax

/*   isTmax - returns 1 if x is the maximum, two's complement number,
 *     and 0 otherwise 
 *   Legal ops: ! ~ & ^ | +
 *   Max ops: 10
 *   Rating: 1
 */
int isTmax(int x) {
   
	return !(x+x+2) & !!(~x);//x+1+x+1溢出并且非全一
	//x:		0111 1111 1111 1111 1111 1111 1111 1111
	//x+1:	1000 0000 0000 0000 0000 0000 0000 0000
	//x+1+x:	1111 1111 1111 1111 1111 1111 1111 1111
	//x+1+x+1:0000 0000 0000 0000 0000 0000 0000 0000
}

6、allOddBits

/*   allOddBits - return 1 if all odd-numbered bits in word set to 1
 *   where bits are numbered from 0 (least significant) to 31 (most significant)
 *   Examples allOddBits(0xFFFFFFFD) = 0, allOddBits(0xAAAAAAAA) = 1
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 12
 *   Rating: 2
 */
int allOddBits(int x) {
   	
	x = (x>>16) & x;	
	x = (x>>8) & x;		
	x = (x>>4) & x;		
	x = (x>>2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值