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?
A promotion to
intoccurs onbytebecause 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 intobyteis a demotion to the unsigned 8-bit value01010011, losing the most significant 24 bits. The end result is interpreted as83in an unsigned representation.