按位“~” C# 中的运算符

发布于 2024-11-26 12:24:07 字数 310 浏览 3 评论 0原文

考虑这个单元测试代码:

    [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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ㄖ落Θ余辉 2024-12-03 12:24:07

byte 上会升级为 int,因为没有为它们定义二进制补码。

请参阅按位和的文档移位运算符数字促销

本质上,当您对无符号 8 位值 10101100 调用 ~ 时,它会被提升为 32 位有符号值 0...010101100 。它的补码是 32 位值 1...101010011,对于 int 等于 -173。将此结果转换为 byte 会降级为无符号 8 位值 01010011,丢失最高有效的 24 位。最终结果被解释为无符号表示形式的 83

A promotion to int occurs on byte 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 value 10101100, it is promoted to the 32-bit signed value 0...010101100. Its complement is the 32-bit value 1...101010011, which is equal to -173 for int. A cast of this result into byte is a demotion to the unsigned 8-bit value 01010011, losing the most significant 24 bits. The end result is interpreted as 83 in an unsigned representation.

梦在深巷 2024-12-03 12:24:07

因为 ~ 返回一个 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 on byte.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文