按位“~” C# 中的运算符
考虑这个单元测试代码:
[TestMethod]
public void RunNotTest()
{
// 10101100 = 128 + 32 + 8 + 4 = 172
byte b = 172;
// 01010011 = 64 + 16 + 2 + 1 = 83
Assert.AreEqual(83, (byte)~b);
}
该测试通过了。但是,如果没有字节转换,它将失败,因为“~”运算符返回值 -173。这是为什么呢?
Consider this unit test code:
[TestMethod]
public void RunNotTest()
{
// 10101100 = 128 + 32 + 8 + 4 = 172
byte b = 172;
// 01010011 = 64 + 16 + 2 + 1 = 83
Assert.AreEqual(83, (byte)~b);
}
This test passes. However without the byte cast it fails because the "~" operator returns a value of -173. Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
byte
上会升级为int
,因为没有为它们定义二进制补码。请参阅按位和的文档移位运算符 和 数字促销。
本质上,当您对无符号 8 位值
10101100
调用~
时,它会被提升为 32 位有符号值0...010101100
。它的补码是 32 位值1...101010011
,对于int
等于 -173。将此结果转换为byte
会降级为无符号 8 位值01010011
,丢失最高有效的 24 位。最终结果被解释为无符号表示形式的83
。A promotion to
int
occurs onbyte
because binary complement is not defined for them.See the documentation for bitwise and shift operators and numeric promotions.
Intrinsically, when you call
~
on the unsigned 8 bit value10101100
, it is promoted to the 32-bit signed value0...010101100
. Its complement is the 32-bit value1...101010011
, which is equal to -173 forint
. A cast of this result intobyte
is a demotion to the unsigned 8-bit value01010011
, losing the most significant 24 bits. The end result is interpreted as83
in an unsigned representation.因为
~
返回一个 int。请参阅~ 运算符(C# 参考)< /a> (MSDN)它仅针对
int、uint、long 和 ulong
进行预定义 - 因此在byte
上使用它时会存在隐式转换。Because
~
returns an int. See ~ Operator (C# Reference) (MSDN)It is only predefined for
int, uint, long, and ulong
- so there is an implicit cast when using it onbyte
.