I’ve just started struggling around C# and I have a question.
In the following code:
byte var = 0;
Console.WriteLine("{0}", ~var);
Why does it print -1? From http://www.csharp-station.com/Tutorial/CSharp/Lesson02 I’ve read that the byte range is from 0 to 255 and ~(00000000)_2 gives (11111111)_2 which is equal to (255)_10.
The value you are printing is not of type
byte. It is of typeint.The
~(bitwise not) operator is not defined forbyte, but it is forint. Your code has an implicit widening conversion toint. Your code is roughly equivalent to this version that uses an explicit cast:The bitwise not operator inverts the bits to give the result
111....111(base 2). This has the value -1 in the two’s complement representation.If you want the result to be a byte with value 255 you have to add an explicit cast: