1:bit_and(x, y) 只用~与|实现x&y 2:get_byte(x, n) 获取x的第n各字节 3:logical_shift(x, n) 逻辑右移 4:bit_cnt(x) x二进制表示中1的个数 5:not(x) 不使用!运算符实现!x 6:tmin() 最小的有符号数(32位) 7:fits_bits(x, n) n位二进制补码能表示x吗? 8:divpwr2(x, n) 计算x/2 n 9:neg(x) 不用-运算符实现-x 10:is_positive(x) x > 0? 11:is_le(x, y) x <= y? 12:floor_log2(x) 计算不超过log2x的整数 13:float_neg(uf) 计算-f 14:float_i2f(x) 求x的位级表示 15:float_scalce2(uf) 计算2倍的f 。用c语言完成并给出详细的代码
时间: 2023-10-24 15:07:45 浏览: 158
1.
```
int bit_and(int x, int y) {
return ~(~x | ~y);
}
```
2.
```
int get_byte(int x, int n) {
return (x >> (n << 3)) & 0xFF;
}
```
3.
```
int logical_shift(int x, int n) {
return (unsigned)x >> n;
}
```
4.
```
int bit_cnt(int x) {
int cnt = 0;
while (x) {
cnt++;
x &= x - 1;
}
return cnt;
}
```
5.
```
int not(int x) {
return ~x + 1;
}
```
6.
```
int tmin() {
return 1 << 31;
}
```
7.
```
int fits_bits(int x, int n) {
int shift = 32 + (~n + 1);
return (x << shift >> shift) == x;
}
```
8.
```
int divpwr2(int x, int n) {
int sign = x >> 31;
return (x + (sign << n) - sign) >> n;
}
```
9.
```
int neg(int x) {
return ~x + 1;
}
```
10.
```
int is_positive(int x) {
return !((x >> 31) & 1) && !!x;
}
```
11.
```
int is_le(int x, int y) {
int sign_x = x >> 31;
int sign_y = y >> 31;
return (sign_x & !sign_y) || (!(sign_x ^ sign_y) && ((y + ~x + 1) >> 31) & 1);
}
```
12.
```
int floor_log2(int x) {
int bit_cnt = !!x;
bit_cnt |= !!(x >> 16) << 4;
bit_cnt |= !!(x >> (bit_cnt << 1)) << 3;
bit_cnt |= !!(x >> (bit_cnt << 1 >> 1)) << 2;
bit_cnt |= !!(x >> (bit_cnt << 1 >> 2)) << 1;
bit_cnt |= !!(x >> (bit_cnt << 1 >> 3)) << 0;
return bit_cnt + (~0);
}
```
13.
```
unsigned float_neg(unsigned uf) {
int sign = uf >> 31;
if (sign == 1) {
return uf;
} else {
return uf + (1 << 31);
}
}
```
14.
```
float float_i2f(int x) {
int sign = x >> 31;
int exp, frac;
if (sign == 0) {
if (x == 0) {
return 0;
} else {
int tmp = x, cnt = 0;
while (tmp >> cnt) {
cnt++;
}
cnt--;
exp = cnt + 127;
tmp &= ~(1 << cnt);
tmp <<= 9 - cnt;
frac = tmp & 0x7FFFFF;
}
} else {
x = ~x + 1;
int tmp = x, cnt = 0;
while (tmp >> cnt) {
cnt++;
}
cnt--;
exp = cnt + 127;
tmp &= ~(1 << cnt);
tmp <<= 9 - cnt;
frac = tmp & 0x7FFFFF;
}
return (sign << 31) | (exp << 23) | frac;
}
```
15.
```
unsigned float_scale2(unsigned uf) {
if ((uf & 0x7F800000) == 0x7F800000) {
return uf;
} else if ((uf & 0x7F800000) == 0) {
return (uf & 0x007FFFFF) << 1 | (uf & 0x80000000);
} else {
return uf + (1 << 23);
}
}
```
阅读全文