C# 反码操作
对于
byte x = 1;
Console.WriteLine(~x);
输出的结果是 -2
这是因为位操作符的重载有限,只能用于6种特定数据类型int、uint、long、ulong、bool和枚举
1实际上是
0000 0001
当我们对byte类型取反前,该数据类型会转换为最匹配的类型int(通常我们称之为numeric promotion)
0000 0000 0000 0000 0000 0000 0000 0001
取反的结果如下,相当于int类型的-2
1111 1111 1111 1111 1111 1111 1111 1110
如果我们写的是
byte x = 1;
byte y = ~x;
Console.WriteLine(y);
那么就会得到一个编译时错误,Cannot implicitly convert type 'int' to 'byte',而事实上byte是无符号8位整数,范围为0~255,是不可能为负数的
为了修正这个问题,我们可以使用
byte x = 1;
byte y = (byte)~x;
Console.WriteLine(y);
这样实际得到是1111 1110,也就是最终结果为254