Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative value in byte type

Tags:

c#

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.

like image 809
tobi Avatar asked May 27 '26 08:05

tobi


1 Answers

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;
like image 156
Mark Byers Avatar answered May 30 '26 10:05

Mark Byers