Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise "~" Operator in C#

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?

like image 552
S. Valmont Avatar asked Jul 25 '11 02:07

S. Valmont


People also ask

What is bitwise operator in C language?

What is a Bitwise Operator? The Bitwise Operator in C is a type of operator that operates on bit arrays, bit strings, and tweaking binary values with individual bits at the bit level. For handling electronics and IoT-related operations, programmers use bitwise operators. It can operate faster at a bit level.

What does bitwise & do in C?

The bitwise AND & operator returns 1 if and only if both the operands are 1. Otherwise, it returns 0. The following table demonstrates the working of the bitwise AND operator. Let a and b be two operands that can only take binary values i.e. 1 and 0.


2 Answers

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.

like image 187
Tugrul Ates Avatar answered Sep 25 '22 05:09

Tugrul Ates


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.

like image 45
Yahia Avatar answered Sep 26 '22 05:09

Yahia