简体   繁体   中英

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

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

byte a = 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM