计算机系统基础的第二次上机作业
-
简介
熟悉整型和浮点型数据的编码方式,熟悉C/C++中的位操作运算。 -
要求
请按照要求补全 bits.c 中的函数,并进行验证。包括以下7个函数:
a. int conditional(int x, int y, int z)
功能:实现与三目运算符表达式 x ? y : z 具有等价功能的函数 合法的运算符:! ~ & ^ | + << >> 可使用的运算符数:16 难度:4
#endif
/*
* conditional - same as x ? y : z
* Example: conditional(2,4,5) = 4
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 16
* Rating: 3
*/
int conditional(int x, int y, int z) {
return ((!x+~1+1)&y)|((~!x+1)&z);
}
若x为非0,return y;
(!x+1+1)&y)置1,(!x+1)&z)置0;
b. int isNonNegative(int x)
功能:当 x >=0 时,返回1;否则返回0 合法的运算符:! ~ & ^ | + << >> 可使用的运算符数:6 难度:3
/*
* isNonNegative - return 1 if x >= 0, return 0 otherwise
* Example: isNonNegative(-1) = 0. isNonNegative(0) = 1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 6
* Rating: 3
*/
int isNonNegative(int x) {
return !(x>>31);
}
x右移31位,得到符号为,若符号位为1,则返回0,否则返回1。
c. int isGreater(int x, int y)
功能:当 x > y 时,返回1,否则返回0 合法的运算符:! ~ & ^ | + << >> 可使用的运算符数:24 难度:3
/*
* isGreater - if x > y then return 1, else return 0
* Example: isGreater(4,5) = 0, isGreater(5,4) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 24
* Rating: 3
*/
int isGreater(int x, int y) {
int mask_x,mask_y,sub;
mask_x=x>>31;
mask_y=y>>31;
sub=(x+~y)>>