tobi
tobi

Reputation: 2002

Negative value in byte type

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.

Upvotes: 3

Views: 2284

Answers (1)

Mark Byers
Mark Byers

Reputation: 838116

The value you are printing is not of type byte. It is of type int.

The ~ (bitwise not) operator is not defined for byte, but it is for int. Your code has an implicit widening conversion to int. Your code is roughly equivalent to this version that uses an explicit cast:

int temp = ~((int)var);
Console.WriteLine("{0}", temp);

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:

byte x = 0;
byte result = (byte)~x;

Upvotes: 6

Related Questions