开发者

C# XOR operators: ^ vs ^= and implicit type conversion

I've noticed something odd about using the bitwise XOR operator on bytes in C#. Odd to my mind, at least.

byte a 开发者_StackOverflow= 0x11;
byte b = 0xAA;
a ^= b;         // works
a = a ^ b;      // compiler error: Cannot implicitly convert type "int" to "byte"

I also see this issue using short, but not int or long.

I thought the last two lines were equivalent, but that doesn't seem to be the case. What's going on here?


There is no xor operator that takes and returns bytes. So C# implicitly widens the input bytes to ints. However, it does not implicitly narrow the result int. Thus, you get the given error on the second line. However, §14.14.2 (compound assignment) of the standard provides that:

if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.

x and y (the inputs) are both bytes. You can explicitly narrow a int to a byte, and clearly a byte is implicitly convertible to a byte. Thus, there is an implicit cast.


In most C-like languages, operators will promote types smaller than int to int.

In such languages, a op= b is equivalent to a = (typeof a)(a op b)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜