如果不能用if,那么用-1是个非常好的处理手段
结果:
目录
题目总描述:(作为英语练习还是非常好的)
/*
* CS:APP Data Lab
*
* <Please put your name and userid here>
* 王雅贤 wangyaxian_2022150054
* 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
1.bitXor
//1
/*
* 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));
}
思路:
//求异或
//任意位相异即可
//(x&~y)|(~x&y) 左式或者右式对应位为1即为1
//
//去思考如何转换:(这里左右是基于上式的)
//左右 & ~后的左右 &
//0 0 0 1 1 1
//1 0 0 0 1 0
//0 1 0 1 0 0
//1 1 1 0 0 0
//我们或运算的结果是后三行为1,我们发现按位取反后后三行都是**一样的**
//而那个结果再次按位取反即可。
//
//~ (~()&~())
2.tmin
/*
* tmin - return minimum two's complement integer
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 4
* Rating: 1
*/
int tmin(void) {
return 1<<31;
}
//原码 负的2^31:
//原码 11111111
//反码 10000000
//补码 10000001
//
//-0:
//其实 10000000更小...
// 2^31 + 1
//
3.isTmax
//2
/*
* isTmax - returns 1 if x is the maximum, two's complement number,
* and 0 otherwise
* Legal ops: ! ~ & ^ | +
* Max ops: 10
* Rating: 2
*/
int isTmax(int x) {
return !(~(x^(x+1)) + !(x+1));
}
//先看INT_MAX,性质是+1后恰好所有位都不同
// 0111 +1 == 1000
// 两者^ == 1111 (只有全1按位取反才是0)
// 0101 +1 == 0110
// 两者^ == 0011
// 0001 +1 == 0010
// ^ == 0011
// 1111 +1 == 0000
// ^ == 1111
// 因为-1也有这种特殊性质,所以需要额外加一步来区分
// !(0+0) == 1
// 必须两式都为0,右边0用于区分-1
4.allOddBits
/*
* allOddBits - return 1 if all odd-numbered bits in word set to 1
* Examples allOddBits(0xFFFFFFFD) = 0, allOddBits(0xAAAAAAAA) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 12
* Rating: 2
*/
int allOddBits(int x) {
int aim = 0xAAAAAAAA;
return !((x&aim)^aim);
}
所有奇数位为1
/*
A 1010
1234
D 1101
检测奇数位全为1
偶数位不用管,先排除干扰。然后异或看是否有异
*/
5.negate
/*
* negate - return -x
* Example: negate(1) = -1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int negate(int x) {
return (~x)+1;
}
/*
正数按位取反加一可以变成负数的补码
**负数同样操作可以变为正数**
*/
6.isAsciiDigit
//3
/*
* isAsciiDigit - return 1 if 0x30 <= x <= 0x39 (ASCII codes for characters '0' to '9')
* Example: isAsciiDigit(0x35) = 1.
* isAsciiDigit(0x3a) = 0.
* isAsciiDigit(0x05) = 0.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 3
*/
int isAsciiDigit(int x) {
return (!((x+(~0x30 + 1))>>31)) & (!!((x+(~0x3a + 1))>>31));
}
/*
0011 0000
0011 0101
直接减看符号位
*/
7.conditional
/*
* 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 + ~0)&y) | ((!!x + ~0)&z);
}
x为true返回y,为false返回z
/*
111111111 + 1 == 0
!x + ~0
*/
8.isLessOrEqual
/*
* 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) {
return (
!((y+~x+1)&(1<<31))
| ( (!(y&(1<<31))) & !!(x&(1<<31)) ))
& !( !!(y&(1<<31)) & (!(x&(1<<31))));
}
/*
减完看符号位
x <= y <=> y >= x
y - x 符号位为0 为 真
---溢出情况:
y x
1.
很大正数-负数 ,可能发生溢出而得不到正确的值
符号位 0
溢出后 1
2.
负数 正数
11000 - 01111
+ 10001
符号位应为 1
溢出后可能为 0 有可能进位成正数
这种情况希望返回0 ,所以&上这种情况发生时的0
*/
9.logicalNeg
//4
/*
* logicalNeg - implement the ! operator, using all of
* the legal operators except !
* Examples: logicalNeg(3) = 0, logicalNeg(0) = 1
* Legal ops: ~ & ^ | + << >>
* Max ops: 12
* Rating: 4
*/
int logicalNeg(int x) {
return ~((~x+1) |x)>>31&1;
}
0和按位取反加一后的值 按位或,符号位仍为0
负数不用说了符号位都是1,
正数取反符号位也都是1了
/*
0 按位取反加一符号位还是0
100001 也是
< 0 原位也是 0>
正数:
0########
1~~~~~~~~
符号位仍为1
负数:
1#######
0~~~~~~~
符号位仍为1
100000
011111
*/
10.howManyBits
/* 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 mask = x >> 31;
x = (~mask & x) | (mask & ~x);
int cnt16,cnt8,cnt4,cnt2,cnt1;
cnt16 = cnt8 = cnt4 = cnt2 = cnt1 = 0;
int y = x >> 16;
cnt16 = !!y << 4;//前面有1,那么后面16位都要,2的4次方
//x = x >> (16& (~0 + !!!y)); 用1或0来判断是否移动,不过cnt16是16或0,直接写cnt16即可。。
x = x >> cnt16;
cnt8 = !!(x>>8) << 3;
x = x >> cnt8;
cnt4 = !!(x>>4) << 2;
x = x >> cnt4;
cnt2 = !!(x>>2) << 1;//现在4个,看后面两个要不要
x = x >> cnt2;
cnt1 = !!(x>>1);// 00
x = x >> cnt1;
//x 1
return cnt16 + cnt8 + cnt4 + cnt2 + cnt1 + x + 1;
}
/*
右移自动扩充符号位的意思
12 8+4 01100
298 0001 0010 1010
-5 4 + 1
1101
1010
1011
100000000000000000101
111111111111111111010
111111111111111111011
给的补码,我们按位取反后处理
000000000000000000100
正数最前面要留一个0,负数符号位要1个
0 0
-1 1
8 1000
——————
mask = x>>31;符号位,全零或全一
对于正数,mask就是全0,~mask就是全一。负数相反。
所以“正数不变,负数按位取反”是
x = (~mask & x) | (mask & ~x);
一直二分来计数:
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000
0000 0000
0000
00
*/
11.float_twice
//float
/*
* 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) {
if((uf &0x7F800000) == 0x7f000000)
{
return 0x7f800000| (uf&(1<<31));
}
if((uf&0x7F800000) == 0)
{
uf = ((uf & 0x007fffff) << 1) | (uf & 0x80000000);
}
else if((uf&0x7F800000) != 0x7F800000)
{
uf = uf + 0x800000;
}
return uf;
}
/*
0 00000000 000000000000000000000
规格化指数位加一即可
0111 1111 1
*/
12.float_i2f
/*
* 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) {
if (x == 0)return 0;
//if (x == 0x80000000)return 0xcf000000;
int ret = 0;
ret |= x & (1 << 31);
int mask = x >> 31;
x = (~mask & x) | (mask & (~x + 1));//去符号位
int fpos = 31;
while (!(x & (1 << fpos))) fpos = fpos - 1;
fpos = fpos + 1;
x ^= (1 << (fpos - 1));//去掉第一位
int exp = 127;//exponent
//2^8 == 256
if (fpos > 24)//要舍入
{
//fpos + 23 + ...
//fpos == 25 ,要舍1位,为25-24
int lastval = 0;//先是mask
int lastnum = fpos - 24;
while (lastnum--)
{
lastval = (lastval << 1) + 1;
}
lastval &= x;
//向偶数舍入,指的是前面的数是奇数还是偶数,比如7.5向8,8.5向8
//对应二进制结尾,是1就+1,不然就不动
x >>= fpos - 24;
if (lastval & (1 << (fpos - 24-1)))
{
if (lastval ^ (1 << (fpos - 24-1))||(x&1))
{
if (x == 0x7fffff)
{
x = 0;
exp += 1;
}
else
x += 1;
}
}
//else//尾数不用舍入
}
else//让第二位在23位
x <<= 24 - fpos;
exp += fpos - 1;
//31 30 ... 7 ... 0
exp <<= 23;
ret |= exp;
ret |= x;
return ret;
}
/*
int强制转化成将浮点数
32
1 8 23
超过23位就要舍入
首位是第几位,就右移 n-1位,让首位为1.XX的1
(
向偶数舍入:
舍去的第一位为1,就进位
因为最后一位除以二,就是 >> 1 ,也就是下一位。
*/
13.float_f2i
/*
* float_f2i - Return bit-level equivalent of expression (int) f
* for floating point argument f.
* Argument is passed as unsigned int, but
* it is to be interpreted as the bit-level representation of a
* single-precision floating point value.
* Anything out of range (including NaN and infinity) should return
* 0x80000000u.
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 30
* Rating: 4
*/
int float_f2i(unsigned uf) {
//if (uf == 0x0)return 0;
//if (uf == 0x80000000)return 0;
if ((uf & 0x7f800000) == 0x7f800000)
return 0x80000000;
int ret;
int sign;
ret = sign = uf & (0x80000000);
int exp = (uf & 0x7f800000) >> 23;
if ((158 - exp) & 0x80000000)
return 0x80000000;
if ((exp - 127 ) & 0x80000000)
return 0x0;
uf = (uf & (0x007fffff)) | (1 << 23);//现在正在24位
exp = exp - 127;
if (exp < 23)
ret |= uf >> (23 - exp);
else
ret |= uf << (exp - 23);
if (sign)
ret = (~ret + 1) | sign;
return ret;
}
/*
NaN not a number
s 11111111 不是全0
infinity 无限
s 11111111 全0
7f80000
小数不保留:全0的规格化小数
0~31
127以下
溢出: 超过2的31次方。 127+31 == 158
158: 1001 1110
30 23
*/