在做C语言的Datalab实验时有几个函数的功能看不明白,在网上找到了大神的代码,但是还是看不太懂,请教各位大神以下4个函数的作用以及代码
/*
- 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 result;
//int mask1=(0x55)|(0x55<>1)&mask1);
//add every four bits
result=(result&mask2)+((result>>2)&mask2);
//add every eight bits
//result=(result&mask3)+((result>>4)&mask3);
result=(result+(result>>4))&mask3;
//add every sixteen bits
//result=(result&mask4)+((result>>8)&mask4);
result=(result+(result>>8))&mask4;
//add every thirty two bits
//result=(result&mask5)+((result>>16)&mask5);
result=(result+(result>>16))&mask5;
return result;
}
/*
- fitsBits - return 1 if x can be represented as an
- n-bit, two's complement integer.
- 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 shiftNumber = ~n + 33;
return !(x^((x << shiftNumber) >> shiftNumber)); }
unsigned float_i2f(int x) { //??????
unsigned shiftLeft = 0;
unsigned afterShift, tmp, flag;
unsigned absX = x;
unsigned sign = 0;
//special case
if (x == 0) return 0;
//if x < 0, sign = 1000...,abs_x = -x
if (x < 0) {
sign=0x80000000;
absX = -x;
}
afterShift=absX;
//count shift_left and after_shift
while (1) {
tmp = afterShift;
afterShift<<=1;
shiftLeft++;
if (tmp & 0x80000000) break;
}
if ((afterShift & 0x01ff) > 0x0100)
flag = 1;
else if ((afterShift & 0x03ff) == 0x0300)
flag = 1;
else
flag = 0;
return sign + (afterShift >> 9) + ((159 - shiftLeft) << 23) + flag;
}
/*
- 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) { //????? unsigned f=uf;
/ Computer 2*f. If f is a NaN, then return f. /
if ((f & 0x7F800000) == 0){
//shift one bit to left
f = ((f & 0x007FFFFF) << 1) | (0x80000000 & f);
}
else if ((f & 0x7F800000) != 0x7F800000){
/ Float has a special exponent. /
/ Increment exponent, effectively multiplying by 2. */
f = f + 0x00800000;
}
return f;
}