2020-03-25在自己博客园搬运过来…
Homework Problems
2.57
void show_short(short x)
{
show_bytes((byte_pointer) &x, sizeof(short));
}
void show_long(long x)
{
show_bytes((byte_pointer) &x, sizeof(long));
}
void show_double(double x)
{
show_bytes((byte_pointer) &x, sizeof(double));
}
2.58
int is_little_endian()
{
int a = 1;
/*
&a: 取a的地址
(char*)&a: 将a的地址所在的位置的值视为字符型指针的地址
*(char*)&a: 取a所在地址的第0个字节的值作为一个char类型返回
*/
return *(char*)&a;
}
2.59
result = (x & 0xFF) | (y & (~0xFF));
2.60
unsigned replace_byte(unsigned x, int i, unsigned char b)
{
int j;
unsigned char c;
j = 8 * i;
b = b << j;
c = ~(0xFF << j);
return ((x & c) | b);
}
2.61
//A
bool result = !(x + 1);
//B
bool result = !x;
//C
bool result = !(~(x | (~0xFF)));
//D
bool result = !(~(x >> ((sizeof(int) - 1) << 3)));
2.62
bool shifts_are_arithmetic()
{
/*这里不能写x = 0xFFFFFFFF,因为int不一定是32位的*/
int x = -1;
return !(x ^ (x >> ((sizeof(int)));
}
2.63
unsigned srl(unsigned x, int k)
{
/*Perform shift arithmetically*/
unsigned xsra = (int)x >> k;
int w = sizeof(int) << 3;
unsigned y = 2 << (w - k - 1);
return (y - 1) & xsra;
}
int sra(int x, int k)
{
/*Perform shift logically*/
int xsrl = (unsigned)x >> k;
int w = sizeof(int) << 3;
int y = -1 << (w - k - 1);
int z = (~((xsrl & y) + y) & y) << 1;
return xsrl | z;
}
2.64
int any_odd_one(unsigned x)
{
return !(~(x | 0x55555555));
}
2.65
/*Return 1 when x contains an odd number of 1s; 0 otherwise. Assume w = 32*/
int odd_ones(unsigned x)
{
x ^= x >> 1;
x ^= x >> 2;
x ^= x >> 4;
x ^= x >> 8;
x ^= x >> 16;
return x & 1;
}
2.66
/*Generate mask indicating leftmost 1 in x. Assume w = 32
*For example, 0xFF00->0x8000, and 0x6600->0x4000.
*If x = 0, then return 0.
*/
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
Right shift, only with shift amounts between 0 and w - 1, and w is 32.
//B
int int_size_32()
{
int set_msb = 1 << 31;
int beyond_msb = 2 << 31;
return set_msb && !beyond_msb;
}
//C
int int_size_16()
{