开发者

Bitwise "~" Operator in C#

开发者 https://www.devze.com 2023-03-22 20:08 出处:网络
Consider this unit test code: [TestMethod] public void RunNotTest() { // 10101100 = 128 + 32 + 8 + 4 = 172

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 cas开发者_如何学JAVAt it fails because the "~" operator returns a value of -173. Why is this?


A promotion to int occurs on byte because binary complement is not defined for them.

See Unary numeric promotions and Bitwise complement operator.

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消