是按位运算在有符号整数,结果界定? [英] Are the results of bitwise operations on signed integers defined?
问题描述
我知道的行为>>
签署整数可以是依赖于实现(具体而言,当左操作数为负)
I know that the behavior of >>
on signed integer can be implementation dependent (specifically, when the left operand is negative).
怎么样的人:〜
,>>
,&放大器;
, ^
, |
?
当他们的操作数有符号的整数内置型(短
, INT
,长
,长长
),保证是相同的(中位内容方面)的结果,如果他们的类型是无符号的?
What about the others: ~
, >>
, &
, ^
, |
?
When their operands are signed integers of built-in type (short
, int
, long
, long long
), are the results guaranteed to be the same (in terms of bit content) as if their type is unsigned?
推荐答案
有关的负面操作数,<<
是未定义行为和结果>>
是实现定义(通常为算术右移)。 <<
和>>
在概念上是不是位运算符。他们是算术运算符相当于乘除通过两个在其上他们明确的操作数的合适的电源。
For negative operands, <<
has undefined behavior and the result of >>
is implementation-defined (usually as "arithmetic" right shift). <<
and >>
are conceptually not bitwise operators. They're arithmetic operators equivalent to multiplication or division by the appropriate power of two for the operands on which they're well-defined.
至于真正的位运算符 ^
,〜
, |
和&安培;
,他们对位重的(可能晋升)类型的操作数的值的presentation操作。有符号重新presentation的每个可能的选择他们的研究结果明确定义(二进制补码,的补,或登录幅度),但在后两种情况下,它可能是其结果将是一个陷阱重新presentation如果实施对待零负重presentation为陷阱。就个人而言,我几乎总是使用符号前pressions有位运算符,这样的结果是的值的而不是重新presentations 的方面100%的明确定义
As for the genuine bitwise operators ^
, ~
, |
, and &
, they operate on the bit representation of the value in the (possibly promoted) type of the operand. Their results are well-defined for each possible choice of signed representation (twos complement, ones complement, or sign-magnitude) but in the latter two cases it's possible that the result will be a trap representation if the implementation treats the "negative zero" representation as a trap. Personally, I almost always use unsigned expressions with bitwise operators so that the result is 100% well-defined in terms of values rather than representations.
最后,请注意书面可能只适用于C. C和C ++这个答案是非常不同的语言,虽然我不知道C ++不好,我理解它可能在某些这些地区的不同从C ...
Finally, note that this answer as written may only apply to C. C and C++ are very different languages and while I don't know C++ well, I understand it may differ in some of these areas from C...
这篇关于是按位运算在有符号整数,结果界定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!