深入理解计算机系统实验二 datalab
深入理解位运算的一个实验……参考了网上dalao的实现方式,其中感觉最巧妙的就是bitCount的二分思想,这里附上链接
http://blog.chinaunix.net/uid-20729605-id-1884367.html
http://blog.chinaunix.net/uid-20729605-id-1884368.html
自己在做的时候遇上的麻烦:
1.同一种变量要一次性定义完,比如int a,b,c;而不能int a;int b;int c;(是C++给惯的)
2.需要把文件弄到虚拟机里面,所以要下载安装VMwareTool,然后就可以直接拖进去了。
3.自己写函数的时候特别要注意细节,有符号到无符号的转换,考虑移位后符号位的填充,特判0和Nan和inf等……
实验过程:
1.把实验文件中的bits.c补充完整
2.下完Vmware Tools之后把实验完成的文件拖到虚拟机的home文件夹
2.打开终端,输入cd datalab-handout进入文件夹
3.输入 ./dlc -e bits.c可以查看是否有错,符号是否超出限制
4.输入make btest创建测试文件
5.如果之前创建了btest,后来又修改了bits.c,先输入make clean,再输入btest去重新创建测试程序
会出现几个警告,不用管他
6.输入./btest去测试你的bits.c吧
然后实验就愉快的做完了
附上集结各dalao思路的代码以及个人的理解
/*
* CS:APP Data Lab
*
*
* bits.c - Source file with your solutions to the Lab.
* This is the file you will hand in to your instructor.
*
* WARNING: Do not include the <stdio.h> header; it confuses the dlc
* compiler. You can still use printf for debugging without including
* <stdio.h>, although you might get a compiler warning. In general,
* it's not good practice to ignore compiler warnings, but in this
* case it's OK.
*/
#if 0
/*
* Instructions to Students:
*
* STEP 1: Read the following instructions carefully.
*/
/*
You will provide your solution to the Data Lab by
editing the collection of functions in this source file.
INTEGER CODING RULES:
Replace the "return" statement in each function with one
or more lines of C code that implements the function. Your code
must conform to the following style:
int Funct(arg1, arg2, ...) {
/* brief description of how your implementation works */
/* int var1 = Expr1;
...
int varM = ExprM;
varJ = ExprJ;
...
varN = ExprN;
return ExprR;
}
/*
Each "Expr" is an expression using ONLY the following:
1. Integer constants 0 through 255 (0xFF), inclusive. You are
not allowed to use big constants such as 0xffffffff.
2. Function arguments and local variables (no global variables).
3. Unary integer operations ! ~
4. Binary integer operations & ^ | + << >>
Some of the problems restrict the set of allowed operators even further.
Each "Expr" may consist of multiple operators. You are not restricted to
one operator per line.
You are expressly forbidden to:
1. Use any control constructs such as if, do, while, for, switch, etc.
2. Define or use any macros.
3. Define any additional functions in this file.
4. Call any functions.
5. Use any other operations, such as &&, ||, -, or ?:
6. Use any form of casting.
7. Use any data type other than int. This implies that you
cannot use arrays, structs, or unions.
You may assume that your machine:
1. Uses 2s complement, 32-bit representations of integers.
2. Performs right shifts arithmetically.
3. Has unpredictable behavior when shifting an integer by more
than the word size.
EXAMPLES OF ACCEPTABLE CODING STYLE:
/*
* 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;
// }
/*
* 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;
// }
/*
FLOATING POINT CODING RULES
For the problems that require you to implent floating-point operations,
the coding rules are less strict. You are allowed to use looping and
conditional control. You are allowed to use both ints and unsigneds.
You can use arbitrary integer and unsigned constants.
You are expressly forbidden to:
1. Define or use any macros.
2. Define any additional functions in this file.
3. Call any functions.
4. Use any form of casting.
5. Use any data type other than int or unsigned. This means that you
cannot use arrays, structs, or unions.
6. Use any floating point data types, operations, or constants.
NOTES:
1. Use the dlc (data lab checker) compiler (described in the handout) to
check the legality of your solutions.
2. Each function has a maximum number of operators (! ~ & ^ | + << >>)
that you are allowed to use for your implementation of the function.
The max operator count is checked by dlc. Note that '=' is not
counted; you may use as many of these as you want without penalty.
3. Use the btest test harness to check your functions for correctness.
4. Use the BDD checker to formally verify your functions
5. The maximum number of ops for each function is given in the
header comment for each function. If there are any inconsistencies
between the maximum ops in the writeup and in this file, consider
this file the authoritative source.
/*
* STEP 2: Modify the following functions according the coding rules.
*
* IMPORTANT. TO AVOID GRADING SURPRISES:grading surprised
* 1. Use the dlc compiler to check that your solutions conform
* to the coding rules.
* 2. Use the BDD checker to formally verify that your solutions produce
* the correct answers.
*/
#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) {
return ~((~x)|(~y));
}
/*
* 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 t = n << 3;//n*8 ,获得x要右移的数目
x>>=t;//右移,让要取得的8位位于前8个
return x&(0xff);//只保留x的前八个
}
/*
* 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 t = ~(1<<31) ;//右移是用0补位
t = ((t>>n)<<1)|1;//等价于t右移n-1位,操作完毕后t的前n位为0
x = (x>>n) & t;
return x;
}
/*
* 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) {
int m1 = 0x55;
m1 = m1 | (m1<<8);
m1 = m1 | (m1<<16);//01
x = (x&m1) + ((x>>1)&m1);
m1 = 0x33;
m1 = m1|(m1<<8);
m1 = m1|(m1<<16);
x = (x&m1) + ((x>>2)&m1);
m1 = 0xf;
m1 = m1|(m1<<8);
m1=m1|(m1<<16);
x = (x&m1) + ((x>>4)&m1);
m1 = 0xff;
m1 = m1|(m1<<16);
x = (x&m1) + ((x>>8)&m1);
m1 = 0xff;
m1 = m1|(m1<<8);
x = (x&m1) + ((x>>16)&m1);
return x;
// int m5 = 0xff;
// m5 = m5 | (m5 << 8);
//int ans = (x&m1) + ((x>>1)&m1);
// ans = (ans&m2) + ((ans>>2)&m2);
// ans = (ans&m3) + ((ans>>4)&m3);
// ans = (ans&m4) + ((ans>>8)&m4);
// ans = (ans&m5) + ((ans>>16)&m5);
}//这里有很多可以优化的地方,不过这样写比较容易理解 w_w
/*
* bang - Compute !x without using !
逻辑非
* Examples: bang(3) = 0, bang(0) = 1
* Legal ops: ~ & ^ | + << >>
* Max ops: 12
* Rating: 4
*/
int bang(int x) {
int t = ~x + 1;
x = x|t;//如果x不为0,或完 符号位一定是1
x = x>>31;//如果符号位为1,结果是0xffffffff,否则为0(符号补位)
return x+1;
}
/*
* tmin - return minimum two's complement integer
最小的int
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 4
* Rating: 1
*/
int tmin(void) {
return 1<<31;
}
/*
* fitsBits - return 1 if x can be represented as an
* n-bit, two's complement integer.
n位二进制有符号数能表示x
* 1 <= n <= 32
* Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 2
*/
int fitsBits(int x, int n) {
int t = 32 + (~n) + 1;//32-n
return !(x^((x<<t)>>t));//注意补位,如果输入1,1是会返回0的,
//因为1位二进制不能表示有符号数,需要有符号位
}
/*
* divpwr2 - Compute x/(2^n), for 0 <= n <= 30
* Round toward zero
* Examples: divpwr2(15,1) = 7, divpwr2(-33,4) = -2
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 2
*/
int divpwr2(int x, int n) {//注意不是向下取整,是向0取整,所以要考虑x是否负数
int s = x>>31;//如果x是负数,s为0xffffffff
int t = (1<<n) + (~0);//2^n-1
int b = s&t;//用来修正进位
return (x+b)>>n;
}
/*
* negate - return -x
* Example: negate(1) = -1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int negate(int x) {
return (~x)+1;
}
/*
* isPositive - return 1 if x > 0, return 0 otherwise
* Example: isPositive(-1) = 0.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 8
* Rating: 3
*/
int isPositive(int x) {
return (!((x>>31)&1)) & (!!x);//符号位是0且x不为0
}
/*
* isLessOrEqual - if x <= y then return 1, else return 0
* Example: isLessOrEqual(4,5) = 1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 24
* Rating: 3
*/
int isLessOrEqual(int x, int y) {//考虑x和y是同号还是异号
int sx = (x>>31)&1;
int sy = (y>>31)&1;//得到符号位
int same = ((x + (~y))>>31) & (!(sx ^ sy));
//x + (~y) >> 31 是x-y-1的符号位,需要x和y同号,所以& 一个!(sx^sy)
int dif = sx&(!sy) ;//如果异号,需要x为负,y为正
return same|dif;
}
/*
* ilog2 - return floor(log base 2 of x), where x > 0
* Example: ilog2(16) = 4
求x是由几位二进制表示的,x>0
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 90
* Rating: 4
又是神奇的二分,答案范围1~31,答案是4位二进制,分别考虑答案每一位ww
*/
int ilog2(int x) {
int bitsNumber=0;
bitsNumber=(!!(x>>16))<<4;
bitsNumber=bitsNumber+((!!(x>>(bitsNumber+8)))<<3);
bitsNumber=bitsNumber+((!!(x>>(bitsNumber+4)))<<2);
bitsNumber=bitsNumber+((!!(x>>(bitsNumber+2)))<<1);
bitsNumber=bitsNumber+(!!(x>>(bitsNumber+1)));
//for non zero bitsNumber, it should add 0
//for zero bitsNumber, it should subtract 1
//bitsNumber=bitsNumber+(!!bitsNumber)+(~0)+(!(1^x));//特判0?
return bitsNumber;
}
/*
* float_neg - Return bit-level equivalent of expression -f for
* floating point argument f.
返回 -f 的二进制表示
* Both the argument and result are passed as unsigned int's, but
* they are to be interpreted as the bit-level representations of
* single-precision floating point values.
参数和返回值都是无符号整数,他们被解释成单精度浮点型的二进制表示
* When argument is NaN, return argument.
参数为Nan的时候返回参数,当f的阶码为1尾数非0则为Nan
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 10
* Rating: 2
*/
unsigned float_neg(unsigned uf) {
unsigned t = uf&0x7fffffff;//符号位取0
if(t > 0x7f800000) // 判断阶码全为1且尾数不为0,uf为Nan
return uf;
return uf^(1<<31);//符号位取反
}
/*
* float_i2f - Return bit-level equivalent of expression (float) x
返回int型的x的浮点型二进制表示
* Result is returned as unsigned int, but
* it is to be interpreted as the bit-level representation of a
* single-precision floating point values.
返回值是无符号整数,他被解释成单精度浮点型的二进制表示
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 30
* Rating: 4
*/
unsigned float_i2f(int x) {
unsigned s,shiftleft,t,abs,flag;
s = x&(1<<31);//取得符号位
if(s) abs = -x;//因为已经取得符号,让x变成绝对值
else abs = x;
if(x == 0) return 0;//排除x为0的情况
shiftleft = 0;//左移次数
while(1){
t = abs;
abs<<=1;
shiftleft ++;
if(t & 0x80000000) break;//刚好把最高位的1移掉
}
if ((abs & 0x01ff)>0x0100)//后9位消去的时候要进位
flag=1;
else if ((abs & 0x03ff)==0x0300)//缺省 (向偶数进位)
flag=1;
else
flag=0;
return s + ((159-shiftleft)<<23) + (abs>>9) + flag;
}
/*
* float_twice - Return bit-level equivalent of expression 2*f for
* floating point argument f.
返回浮点型f乘以2的结果
* Both the argument and result are passed as unsigned int's, but
* they are to be interpreted as the bit-level representation of
* single-precision floating point values.
* When argument is NaN, return argument
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 30
* Rating: 4
*/
unsigned float_twice(unsigned uf) {
unsigned f = uf;
if ((f & 0x7F800000) == 0) //如果阶码全为0
{
f = ((f & 0x007FFFFF) << 1) | (0x80000000 & f);//考虑符号位,左移
}
else if ((f & 0x7F800000) != 0x7F800000)//阶码并不是全为1
{
f =f + 0x00800000;//阶码+1
}//其他情况为inf或者nan,不处理直接返回
return f;
}