简体   繁体   English

C#XOR运算符:^ vs ^ =和隐式类型转换

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

I've noticed something odd about using the bitwise XOR operator on byte s in C#. 我注意到在C#中对byte s使用按位XOR运算符有些奇怪。 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 . 我也看到这个问题使用short ,但不是intlong

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. 没有xor运算符接收和返回字节。 So C# implicitly widens the input bytes to ints. 因此C#隐式地将输入字节扩展为整数。 However, it does not implicitly narrow the result int. 但是,它并没有隐含地缩小结果int。 Thus, you get the given error on the second line. 因此,您在第二行得到给定的错误。 However, §14.14.2 (compound assignment) of the standard provides that: 但是, 该标准的 §14.14.2(复合赋值)规定:

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的类型,并且如果y可隐式转换为x的类型或运算符是移位运算符,则操作将被计算为x =(T)(x op y),其中T是x的类型,除了x仅被计算一次。

x and y (the inputs) are both bytes. x和y(输入)都是字节。 You can explicitly narrow a int to a byte, and clearly a byte is implicitly convertible to a byte. 您可以显式地将int缩小为一个字节,显然一个字节可以隐式转换为一个字节。 Thus, there is an implicit cast. 因此,有一个隐含的演员。

In most C-like languages, operators will promote types smaller than int to int . 在大多数类C语言中,运算符会将小于int类型提升为int

In such languages, a op= b is equivalent to a = (typeof a)(a op b) 在这些语言中, a op= b相当于a = (typeof a)(a op b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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