2.71-你刚刚开始在一家公司工作,他们要实现一组过程来操作一个数据结构,要将4个有符号字节封装成一个32位unsigned。一个字中的字节从0(最低有效字节)编号到3(最高有效字节)。

分配给你的任务是:为一个使用补码运算和算术右移的机器编写一个具有如下原型的函数:

接题目:

/* Declaration of data type where 4 bytes are packed
into an unsigned */
typedef unsigned packed_t;
/* Extract byte from word. Return as signed integer */
int xbyte(packed_t word, int bytenum);

也就是说,函数会抽取出指定的字节,再把它符号扩展为一个32位int。
你的前辈(因为水平不够高而被解雇了)编写了下面的代码:

/* Failed attempt at xbyte */
int xbyte(packed_t word, int bytenum)
{
	return (word >> (bytenum << 3)) & 0xFF;
}

开始作答 官方答案(已验证)

题目的意思是将原来有符号数(33 22 11 00,一共4个字节),现要将每一个字节通过符号扩展都封装成一个32位unsigned数。
A.不管bytenum是正数还是负数,都做了零扩展(和官方答案不同)。
B.这里用负数验证的话,会得到-1就是取出了最高位的第一个字节。

#include <stdio.h>
#include <assert.h>

/* Declaration of data type where 4 bytes are packed
into an unsigned */
typedef unsigned packed_t;

int xbyte(packed_t word, int bytenum) {
	/** pay attention when byte we want is negetive *
	* Assume sizeof(unsigned) is 4
	* first shift left 8 * (4 - 1 - bytenum)
	* then arthemetic shift right 8 
	* (4 - 1) reserve signficant bit */ 
	int size = sizeof(unsigned); 
	int shift_left_val = (size - 1 - bytenum) << 3; 
	int shift_right_val = (size - 1) << 3;
	return (int)word << shift_left_val >> shift_right_val; 
}

int main(int argc, char* argv[]) {
	assert(xbyte(0xAABBCCDD, 1) == 0xFFFFFFCC); 
	assert(xbyte(0x00112233, 2) == 0x11);
	return 0;
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

榆钱不知秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值