首页
论坛
专栏
课程

[原创]C语言一题

2010-10-5 01:05 5520

[原创]C语言一题

2010-10-5 01:05
5520


为了方便大家辨别,我人肉OCR一下。
2.71:

You just started working for a company that is implementing a set of procedures
to operatate on a data structure where 4 signed bytes are packed into a 32-bit
unsigned. Bytes within the word are numbered from 0 (least significant) to 3
(most significant). You have been assigned the task of implementing a function
for a machine using two's-complement arithmetic and arithemetic right shifts with
following prototype:

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

/* Extract byte from word. Return as signed integer */
int xbyte(packet_t word, int bytenum);

That is, the function will extract the designed byte and sign extend it to be a
32-bit int.
    Your predecessor (who was fired for incompetence) wrote following cod

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

  A. What is wroing with this code?

  B. Give a correct implementation of the function that uses only left and righ
     shifts, along with one subtraction.

[公告]安全测试和项目外包请将项目需求发到看雪企服平台:https://qifu.kanxue.com

上传的附件:
最新回复 (9)
programfan 2010-10-5 07:14
2
0
A. 不用说了,显然错的。
B. 大概算了一下,目前无法突破减法的次数限制,用了两次减法。等待高人
wil 2010-10-5 07:32
3
0
int xbyte(unsigned word, int bytenum)
{
    unsigned y = 0;

    y = word << ((3 - bytenum) << 3);
    y >>= 24;

    unsigned char sign = (y >> 7) << 7;
    unsigned char val = (unsigned char)((unsigned char)y << 1) >> 1;

    return val - sign;
}

代码写的有点乱,不过貌似结果对的
wil 2010-10-5 07:34
4
0
深入理解计算机系统习题还这么有趣,回头买本做一下
programfan 2010-10-5 07:41
5
0
晕,我以为只能用移位和减法,不能用赋值的。。。能用的那就能做了,先把目标字节用移位方式取干净,然后把该字节原本的符号位用移位方式去掉(这步需要赋值操作),再减去该字节的原始值就ok了。。。
programfan 2010-10-5 07:45
6
0
发现3L也用了两次减法~
wil 2010-10-5 07:51
7
0
嗯,是2次,搞错了

int xbyte(unsigned word, int bytenum)
{
    unsigned y = 0;

    y = (unsigned char)(word >> (bytenum << 3));

    unsigned char sign = (y >> 7) << 7;
    unsigned char val = (unsigned char)((unsigned char)y << 1) >> 1;

    return val - sign;
}
foxabu 13 2010-10-5 10:06
8
0
显然不能够类型转换,否则不如自定义一个struct,或者拷贝到char[]里面返回[bytenum]好了。
wil 2010-10-5 10:28
9
0
[QUOTE=foxabu;867265]显然不能够类型转换,否则不如自定义一个struct,或者拷贝到char[]里面返回[bytenum]好了。[/QUOTE]

嗯,改了下

int xbyte(unsigned word, int bytenum)
{
    unsigned y = (word >> (bytenum << 3));
    y <<= 24;
    y >>= 24;

    unsigned sign = y >> 7;
    sign <<= 8;
    return y - sign;
}
foxabu 13 2010-10-6 04:03
10
0
其实这个题的本意是考眼力:

for a machine using two's-complement arithmetic and arithemetic right shifts with

不过@wil的解法也是对滴,在此膜拜一下。
游客
登录 | 注册 方可回帖
返回