使用C语言中的算术移位运算符执行逻辑移位 [英] Perform logical shift using arithmetic shift operator in C

查看:240
本文介绍了使用C语言中的算术移位运算符执行逻辑移位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在阅读《计算机系统:程序员的视角》这本书.

Right now I am reading the book Computer Systems : Programmer Perspective.

书中的一个问题说要对有符号整数进行逻辑右移,我不知道该如何开始.

One problem in the book says to perform a logical right shift on a signed integer, I can't figure out how to start on this.

以下是本书中的实际问题:

The following is the actual question from the book:

填写以下C函数的代码.

Fill in code for the following C functions.

  • 函数srl使用算术右移(由值xsra给出)执行逻辑右移,然后执行其他操作,不包括右移或除法.

  • Function srl performs a logical right shift using an arithmetic right shift (given by value xsra), followed by other operations not including right shifts or division.

函数sra使用逻辑右移(由值xsrl给出)执行算术右移,然后执行其他操作,不包括右移或除法.

Function sra performs an arithmetic right shift using a logical right shift (given by value xsrl), followed by other operations not including right shifts or division.

您可以使用计算8*sizeof(int)来确定w,即数据类型int中的位数.移位量k的范围可以从0w − 1.

You may use the computation 8*sizeof(int) to determine w, the number of bits in data type int. The shift amount k can range from 0 to w − 1.

unsigned srl(unsigned x, int k) {
    /* Perform shift arithmetically */
    unsigned xsra = (int) x >> k;
    .
    .
    .
}

int sra(int x, int k) {
    /* Perform shift logically */
    int xsrl = (unsigned) x >> k; 
    .
    .
    .
}

希望您现在已经明白了这个问题.

I hope you understand now the question.

推荐答案

我不会为您提供完整的答案,因为这显然是家庭作业,但我会给您一些提示,以帮助您自己解决问题:

I won't give you a complete answer as this is apparently homework, but I'll give you some hints to help you work it out for yourself:

  • 对于N位的逻辑右移,您需要在算术移位后清除结果的前N位

  • for a logical right shift of N bits you need to clear the top N bits of the result after arithmetic shifting

您可以通过应用适当的 mask 清除值中的位,通常使用按位AND或XOR

you can clear bits in a value by applying an appropriate mask, typically using a bitwise AND or XOR

要清除值的前N个位,您需要一个具有N 0s和其余位为1的掩码

to clear the top N bits of a value you need a mask with N 0s and remaining bits 1

您可以使用左移减少W - N位来生成合适的掩码,其中W是单词中的位数(您可以将其计算为W = sizeof(int) * CHAR_BIT;)

you can generate a suitable mask using left shift by W - N bits, where W is the number of bits in a word (which you can calculate as W = sizeof(int) * CHAR_BIT;)

例如逻辑右移2

value              = 10001010
value >>= 2        = 11100010     // arithmetic right shift

mask               = 00111111     // mask has top 2 bits set to 0

value & mask       = 00100010     // apply mask to get logical right shift

最棘手的部分是生成掩码,但是如果您考虑应用 left 移位,以便选择合适的值,也许再进行进一步的按位运算,您很快就会看到一个相当简单的解决方案.

The trickiest part is generating the mask, but if you think about left shifts applied so a suitable value, perhaps followed by one further bitwise operation, you should soon see a fairly simple solution.

这篇关于使用C语言中的算术移位运算符执行逻辑移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆