有不当之处希望各位多多指正!!!!!!
2.58
/********2.58*********/
bool is_little_endian()
{
unsigned int x = 1;
return *((unsigned char*)&x);
}
2.59
(x & 0xFF) | (y & (~0xFF))
/****
*测试程序
****/
void test()
{
int x = 0x89ABCDEF;
int y = 0x76543210;
printf("%x\n",(x & 0xFF) | (y & (~0xFF)));
}
2.60
分析:先将第i个字节清空,再将该字节置为要求的字节
要定位到所给定的字的第i个字节,需要移动的位数为8*i,及i << 3,以下给出函数
/*********2.60**********/
unsigned replace_byte(unsigned x,unsigned char b,int i)
{
int shift = i << 3;
return (x & ~(0xff << shift)) | (b << shift);
}
2.61
每种情况为真对应一个表达式
A. !(~x)
B. !x
C. x >>((sizeof(int) - 1) << 3) == -1
D. !(x & (0xff))
2.62
分析:判断x移位之后是否还是全为1
bool int_shifts_are_logical()
{
int x = ~0x00;
x >>= 1;
return ~x;
}
2.63
int sra(int x,int k)
{
/* Perform shift logically*/
int xsrl = (unsigned) x >> k;
int w = 8 * sizeof(int);
bool flag = (1 << (w - 1)) & x;
flag && (xsrl | ((1 << k) - 1) << (w - k));
return xsrl;
}
unsigned srl(unsigned x, int k)
{
/*Perform shift arithmetically*/
unsigned xsra = (int) x >> k;
int w = 8 * sizeof(int);
k && (xsra &= ((1 << (w - k)) - 1));
return xsra;
}
2.64
/*********2.64*********/
/*Return 1 when any even bit of x equals 1;0 otherwise Assume w=32*/
int any_even_one(unsigned x)
{
return (x & 0xaaaaaaaa) == 0xaaaaaaaa;
}
2.65
/**********2.65**************/
/*return 1 when x contains an even number of 1s;0 otherwise Assume w=32*/
//以下解法参考 WalkingInTheWind 的微博
int even_ones(unsigned x)
{
x ^= x >> 1;
x ^= x >> 2;
x ^= x >> 4;
x ^= x >> 8;
x ^= x >> 16;
return x & 1;
}
巧妙的通过异或操作判断两位,四位,八位,十六位,最后到三十二位有偶数个1
2.66
根据题目提示先将x转换成00...011...11的格式再进行操作
/**********2.66**************/
int leftmost_one(unsigned x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
2.67
A. 当移位数过大时,有的编译器会进行取模操作,有的则不会,故代码不是通用的
B.
int int_size_is_32()
{
int set_msb = 1 << 31;
int beyond_msb = 1 << 32;
return set_msb && !(beyond_msb & ~(0x01));
}
int int_size_is_32()
{
int set_msb = 1 << 15;
int beyond_msb = 1 << 32;
return set_msb && !(beyond_msb & ~(0x01));
}