Chapter 2 Representing and Manipulating Information

这篇博客包含了2.57到2.97的作业问题,涉及计算机科学中信息的表示和操纵。内容涵盖了一些位操作和条件判断,对理解数据类型和内存管理有帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()
{
   
   
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值