个人网站 | 思想驻留地

0%

CS:APP-Datalab 题目及源码

摘录了我在计算机系统基础(Intro to Computer Systems)课程中独立完成的datalab中的习题
共有21个题目,包括bitParity, isPower2, thirdBits, float_i2f, tmix, rotateRight, copyLSB, isNegative, negate, bitMask, float_twice, satMul3, evenBits, greatestBitPos, rotateLeft, sign, howManyBits, isNotEqual, implication, isTmax, addOK(按照文中顺序排序)

题目要求说明


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/* 
* CS:APP Data Lab
*
* <Please put your name and userid here>
*
* 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:
* 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
/* Copyright (C) 1991-2018 Free Software Foundation, Inc.
This file is part of the GNU C Library.

The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses Unicode 10.0.0. Version 10.0 of the Unicode Standard is
synchronized with ISO/IEC 10646:2017, fifth edition, plus
the following additions from Amendment 1 to the fifth edition:
- 56 emoji characters
- 285 hentaigana
- 3 additional Zanabazar Square characters */

题目及源码


bitParity


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* bitParity - returns 1 if x contains an odd number of 0's
* Examples: bitParity(5) = 0, bitParity(7) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 4
*/
int bitParity(int x) {
/*divide x to 2 parts, and using ^ to cut the even number of 0's*/
x ^= x >> 16;
x ^= x >> 8;
x ^= x >> 4;
x ^= x >> 2;
x ^= x >> 1;
return x&0x1;
}

isPower2


1
2
3
4
5
6
7
8
9
10
11
12
13
/*
* isPower2 - returns 1 if x is a power of 2, and 0 otherwise
* Examples: isPower2(5) = 0, isPower2(8) = 1, isPower2(0) = 0
* Note that no negative number is a power of 2.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 4
*/
int isPower2(int x) {
/*x is power of 2 & x is not a negtive number & x is not zero*/
int mask = ~0;//mask = -1;
return (!((x+mask) & x)) & !(x >> 31) & (!!x);
}

thirdBits


1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* 
* thirdBits - return word with every third bit (starting from the LSB) set to 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 8
* Rating: 1
*/
int thirdBits(void) {
/*just construct every 4 bits and add them*/
int x = 0x49;
int y = 0x92;
int z = 0x24;
int p = 0x49;
return x + (y << 8) + (z << 16) + (p << 24);
}

float_i2f


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* 
* float_i2f - Return bit-level equivalent of expression (float) 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) {
/*
calculate sign, exponent and mantissa respectively
pay attention to 2's complement of negative number
pay attention to round of mantissa if larger then 23 bits
pay attention to offset of exponent part
*/
unsigned sign = 0;
unsigned shift_left = 0;
unsigned flag = 0, tmp;
unsigned absX = x;

//turn to "true form" type
if (x == 0) return 0;
if (x < 0) {
sign = 0x80000000;
absX = -x;
}

while (1) {
tmp = absX;
absX <<= 1;
shift_left++;
if (tmp & 0x80000000) break;
}

//use "round to an even number" rule
//to deal with the rightmost 23-bit part
if ((absX & 0x1ff) > 0x100) flag = 1;
else if ((absX & 0x3ff) == 0x300) flag = 1;

//add sign, exponent, and mantissa together
//exponent = 127(offset) + 31 - (shift left -1)
return sign + (absX>>9) + ((159-shift_left) << 23) + flag;
}

tmin


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

rotateRight


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* 
* rotateRight - Rotate x to the right by n
* Can assume that 0 <= n <= 31
* Examples: rotateRight(0x87654321,4) = 0x18765432
* Legal ops: ~ & ^ | + << >>
* Max ops: 25
* Rating: 3
*/
int rotateRight(int x, int n) {
/*take out the rotate-out part and combine with the left*/
int neg1 = ~0;
int negn = ~n + 1;
int right_mask = ~(neg1 << n);
int rotate_out = (x & right_mask) << (32 + negn);//32 + negn = 32 - n
int rotate_remain = x >> n;

//n = 0 then zeroMask = 0xffffffff, otherwise, zeroMask = 0x00000000;
int zeroMask = (~(~((!!n)&0x1) + 1));
rotate_remain &= ~(neg1 << (32 + negn));

//if n = 0, return x, else, return the combination, depending on zeroMake
return (zeroMask & x) | ((~zeroMask) & (rotate_out + rotate_remain));
}

copyLSB


1
2
3
4
5
6
7
8
9
10
11
/* 
* copyLSB - set all bits of result to least significant bit of x
* Example: copyLSB(5) = 0xFFFFFFFF, copyLSB(6) = 0x00000000
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int copyLSB(int x) {
/*using overflow to turn 0xffffffff to all 0*/
return ~(x&0x1) + 1;
}

isNegative


1
2
3
4
5
6
7
8
9
10
11
/* 
* isNegative - return 1 if x < 0, return 0 otherwise
* Example: isNegative(-1) = 1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 6
* Rating: 2
*/
int isNegative(int x) {
/*shift the sign bit directly*/
return (x >> 31) & 0x1;
}

negate


1
2
3
4
5
6
7
8
9
10
11
/* 
* negate - return -x
* Example: negate(1) = -1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int negate(int x) {
/*flip all the bits and add 1*/
return (~x) + 1;
}

bitMask


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* 
* bitMask - Generate a mask consisting of all 1's
* lowbit and highbit
* Examples: bitMask(5,3) = 0x38
* Assume 0 <= lowbit <= 31, and 0 <= highbit <= 31
* If lowbit > highbit, then mask should be all 0's
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 16
* Rating: 3
*/
int bitMask(int highbit, int lowbit) {

//shift all 1 value and using ^ operation, pay attention to the border situation
int move = highbit + 1;
int high_set = 0;
int low_set = 0;
high_set = (~0) << (move);
high_set &= (~((~(move >> 5)) + 1));
low_set = (~0) << (lowbit);
return (high_set ^ low_set) & (~((move + (~lowbit)) >> 31)) ;
}

float_twice


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* 
* float_twice - Return bit-level equivalent of expression 2*f for
* floating point argument f.
* 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) {
/*based on the condition of uf, either NaN, unnormalized or normalized float*/
unsigned sign = (~(uf >> 31)) + 1;
unsigned exponent = (uf >> 23) & 0xff;
unsigned tail = uf & 0x7fffff;
unsigned res = 0;

//argument equals to -0 or +0
if((uf == 0x80000000) || (uf == 0)) return uf;

//argumnet equals to NaN or Inf
else if (exponent == 0xff) return uf;

//argument equals to unnormalized number
else if ((exponent == 0) && (tail != 0)) {
tail <<= 1;
res = (sign <<= 31);
sign = tail >> 23;
tail &= 0x7fffff;
if(sign)
//become normalized number
res |= ((exponent + 1) << 23);
res |= tail;
}
else {
res = (sign <<= 31);//set sign
res |= ((exponent + 1) << 23);
res |= tail;
}
return res;
}

satMul3


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
* satMul3 - multiplies by 3, saturating to Tmin or Tmax if overflow
* Examples: satMul3(0x10000000) = 0x30000000
* satMul3(0x30000000) = 0x7FFFFFFF (Saturate to TMax)
* satMul3(0x70000000) = 0x7FFFFFFF (Saturate to TMax)
* satMul3(0xD0000000) = 0x80000000 (Saturate to TMin)
* satMul3(0xA0000000) = 0x80000000 (Saturate to TMin)
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 25
* Rating: 3
*/
int satMul3(int x) {
/*judge overflow by sign bit, and then construct TMax or Tmin*/
int two_x = x << 1;
int three_x = two_x + x;
int x_sign = x & (0x1 << 31);
int two_sign = two_x & (0x1 << 31);
int three_sign = three_x & (0x1 << 31);

//mark wether sign changes, overflow then mask = 0xffffffff, otherwise, 0x00000000
int mask = ((x_sign ^ two_sign) | (x_sign ^ three_sign)) >> 31;
int x_sign_mask = x >> 31;

int Tmax = (~0) ^ (0x1 << 31);
int Tmin = 0x1 << 31;
//if sign dosen't change, return result, otherwise, return Tmax or Tmin
return (~mask & three_x) | ( mask & (( (~x_sign_mask) & Tmax) | ( (x_sign_mask)&Tmin )) );
}

evenBits


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* 
* evenBits - return word with all even-numbered bits set to 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 8
* Rating: 1
*/
int evenBits(void) {
int x = 0x55;
x <<= 8;
x |= 0x55;
x <<= 8;
x |= 0x55;
x <<= 8;
x |= 0x55;
x <<= 8;
x |= 0x55;
return x;
}

greatestBitPos


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* 
* greatestBitPos - return a mask that marks the position of the
* most significant 1 bit. If x == 0, return 0
* Example: greatestBitPos(96) = 0x40
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 70
* Rating: 4
*/
int greatestBitPos(int x) {
int count = 0;
int xCopy = x;
int xCopy2 = x;
int Count = 0;
count += !!x;
x >>= 8;
count += !!x;
x >>= 8;
count += !!x;
x >>= 8;
count += !!x;
x >>= 8;
count += (( ~1) + 1);
Count = count + count + count + count + count + count + count + count;
xCopy >>= Count;
Count += !!xCopy;
xCopy >>= 1;
Count += !!xCopy;
xCopy >>= 1;
Count += !!xCopy;
xCopy >>= 1;
Count += !!xCopy;
xCopy >>= 1;
Count += !!xCopy;
xCopy >>= 1;
Count += !!xCopy;
xCopy >>= 1;
Count += !!xCopy;
xCopy >>= 1;
Count += !!xCopy;
return (0x1 << (Count + (~1) + 1)) & (~(!!xCopy2) + 1);
}

rotateLeft


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* 
* rotateLeft - Rotate x to the left by n
* Can assume that 0 <= n <= 31
* Examples: rotateLeft(0x87654321,4) = 0x76543218
* Legal ops: ~ & ^ | + << >>
* Max ops: 25
* Rating: 3
*/
int rotateLeft(int x, int n) {
int moveAfter = 0;
int moveLeft = (x >> (33 + (~n))) & (~((~((33 + (~n))>>5)) + 1));
moveLeft &= (~((~0)<<n));
moveAfter = (x << n);
return moveLeft + moveAfter;
}

sign


1
2
3
4
5
6
7
8
9
10
11
12
13
/* 
* sign - return 1 if positive, 0 if zero, and -1 if negative
* Examples: sign(130) = 1
* sign(-23) = -1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 10
* Rating: 2
*/
int sign(int x) {
int sign = x >> 31;
sign |= !!x;
return sign;
}

howManyBits


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* howManyBits - return the minimum number of bits required to represent x in
* two's complement
* Examples: howManyBits(12) = 5
* howManyBits(298) = 10
* howManyBits(-5) = 4
* howManyBits(0) = 1
* howManyBits(-1) = 1
* howManyBits(0x80000000) = 32
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 90
* Rating: 4
*/
int howManyBits(int x) {
int temp=x^(x>>31);//get positive of x;
int isZero=!temp;
//notZeroMask is 0xffffffff
int notZeroMask=(!(!temp)<<31)>>31;
int bit_16,bit_8,bit_4,bit_2,bit_1;
bit_16=!(!(temp>>16))<<4;
//see if the high 16bits have value,if have,then we need at least 16 bits
//if the highest 16 bits have value,then rightshift 16 to see the exact place of
//if not means they are all zero,right shift nothing and we should only consider the low 16 bits
temp=temp>>bit_16;
bit_8=!(!(temp>>8))<<3;
temp=temp>>bit_8;
bit_4=!(!(temp>>4))<<2;
temp=temp>>bit_4;
bit_2=!(!(temp>>2))<<1;
temp=temp>>bit_2;
bit_1=!(!(temp>>1));
temp=bit_16+bit_8+bit_4+bit_2+bit_1+2;//at least we need one bit for 1 to tmax,
//and we need another bit for sign
return isZero|(temp&notZeroMask);
}

isNotEqual


1
2
3
4
5
6
7
8
9
10
/* 
* isNotEqual - return 0 if x == y, and 1 otherwise
* Examples: isNotEqual(5,5) = 0, isNotEqual(4,5) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 6
* Rating: 2
*/
int isNotEqual(int x, int y) {
return !!(~((~x) + y));
}

implication


1
2
3
4
5
6
7
8
9
10
11
12
/* 
* implication - return x -> y in propositional logic - 0 for false, 1
* for true
* Example: implication(1,1) = 1
* implication(1,0) = 0
* Legal ops: ! ~ ^ |
* Max ops: 5
* Rating: 2
*/
int implication(int x, int y) {
return ((!x) | y);
}

isTmax


1
2
3
4
5
6
7
8
9
10
/*
* 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+1+x+1))&(!!(x+1));
}

addOK


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* 
* addOK - Determine if can compute x+y without overflow
* Example: addOK(0x80000000,0x80000000) = 0,
* addOK(0x80000000,0x70000000) = 1,
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 3
*/
int addOK(int x, int y) {
int z = x + y;
int case1 = 0;
int case2 = 0;
z = (z >> 31) & 0x1;
x = (x >> 31) & 0x1;
y = (y >> 31) & 0x1;
case1 = ((x) ^ (y));
case2 = (!((x) ^ (y))) & (!((z) ^ (x)));
return case1 | case2;
}

外部链接

[1]. Computer Systems: A Programmer’s Perspective