向右移位并有符号整数 [英] Right shift and signed integer

查看:163
本文介绍了向右移位并有符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的编译器,下面的伪code(值二进制替换):

On my compiler, the following psuedo code (values replaced with binary):

sint32 word = (10000000 00000000 00000000 00000000);
word >>= 16;

生成一个与位域,如下所示:

produces a word with a bitfield that looks like this:

(11111111 11111111 10000000 00000000)

我的问题,是我可以依靠此行为对所有平台和C ++编译器?

My question, is can I rely on this behaviour for all platforms and C++ compilers?

推荐答案

从以下链接:
<一href="https://www.securecoding.cert.org/confluence/display/sec$c$c/INT34-C.+Do+not+shift+an+ex$p$pssion+by+a+negative+number+of+bits+or+by+greater+than+or+equal+to+the+number+of+bits+that+exist+in+the+operand"相对=nofollow> INT34-C。不要位的负数或大于或等于位中存在的操作数的数目移位的当然pression

From the following link:
INT34-C. Do not shift an expression by a negative number of bits or by greater than or equal to the number of bits that exist in the operand

不合规code为例(右Shift)
结果 E1&GT;&GT; E2 E1 右移 E2 位的位置。如果 E1 有一个无符号的类型,或者 E1 有符号类型和非负值,则结果的值E1 / 2 E2 的商的整数部分。如果 E1 有签署类型和负值,得到的值是实现定义的,可以是一个算术(签字)转变:

或逻辑(符号)转变:

这不符合code例如无法测试右操作数是否大于或等于促进左操作数的宽度,使不确定的行为。

Noncompliant Code Example (Right Shift)
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation defined and can be either an arithmetic (signed) shift:

or a logical (unsigned) shift:

This noncompliant code example fails to test whether the right operand is greater than or equal to the width of the promoted left operand, allowing undefined behavior.

unsigned int ui1;
unsigned int ui2;
unsigned int uresult;

/* Initialize ui1 and ui2 */

uresult = ui1 >> ui2;

作出假设右移是否实现为算术(签字)移位或逻辑(无符号)移也可能导致安全漏洞。见建议<一href="https://www.securecoding.cert.org/confluence/display/sec$c$c/INT13-C.+Use+bitwise+operators+only+on+unsigned+operands"相对=nofollow> INT13-C。使用位运算符只能在无符号运算的。

这篇关于向右移位并有符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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