右移和有符号整数 [英] Right shift and signed integer

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

问题描述

在我的编译器上,下面的伪代码(用二进制替换的值):

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

产生一个像这样:

 (11111111 11111111 10000000 00000000)

我的问题是,我可以依赖于所有平台和C ++编译器的这种行为。

解决方案

从以下链接:


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)

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

解决方案

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

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;

Making assumptions about whether a right shift is implemented as an arithmetic (signed) shift or a logical (unsigned) shift can also lead to vulnerabilities. See recommendation INT13-C. Use bitwise operators only on unsigned operands.

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

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