课程实验报告
课 程 名 称: 计算机组成与结构
实验项目名称: datalab
专 业 班 级: 通信1301班
姓 名:
学 号:
指 导 教 师: 某神
完 成 时 间: 2015 年 4 月 17 日
计算机科学与工程系
1
实验题目:datalab
实验目的:完善bit.c里的各个函数,实现其功能,并通过btest 的测试。
实验环境:个人电脑、linux发行版本。
*实验内容及操作步骤:
第一步:
完善bits.c里的各个函数,代码如下:
(1).bitAnd函数,要求如下:
/*
* bitAnd - x&y using only ~ and |
* Example: bitAnd(6, 5) = 4
* Legal ops: ~ |
* Max ops: 8
* Rating: 1
*/
#思路:摩根定理:ABA| B
#代码:
int bitAnd(int x, int y) {
return ~(~x|~y);
}
(2).getByte函数,要求如下:
/*
* getByte - Extract byte n from word x
* Bytes numbered from 0 (LSB) to (MSB)
* Examples: getByte(01) = 0x56
* Legal ops: ! ~ & ^ |+ << >>
* Max ops: 6
* Rating: 2
*/
#思路:
*****求到x 的第n个byte*****
*首先,最低位字节 (编号为0的字节)保留x 的第n个byte,将word右
移n个byte,即n*8 (n<< )位;
*清除高三位字节的信息而保留最低位字节的信息,即与0xff进行&运算。
#代码:
int getByte(int x, int n) {
int ret=x>>(n<<3); //将x 的第n个byte移到最低byte位
return ret&0xff; //返回最低位信息
2
}
(3).logicalShift函数,要求如下:
/*
* logicalShift - shift x to the right by n, using a logical shift
* Can assume that 0 <= n <= 31
* Examples: logicalShift(04) = 0
* Legal ops: ! ~ & ^ |+ << >>
* Max ops: 20
* Rating:
*/
#思路:
*****逻辑右移即将所补高位置0*****
*考虑所要处理的有负数和非负数两种情况,即对符号位进行处理:
*设某数为sxxx...,算术右移的结果为sss...sssxxxx... (n+1个s);
*提取出来其符号位t=s<<31,即s000...000,再右移n-1位得到
sss...ssss0...000 (n个s);