Problem - Negative number when Inverting Integer using the ~ operator

Hi,
I am trying to use the bitwise ~ operator to invert a value of 254, but instead of giving me 1, it give me -255. Why is this?
Thank you ,
Tom

Try inverting “unsigned integer”.

Edit. Actually use byte instead of int if you want ~254 = 1

Hi,
Thanks for the quick reply. I am trying this:

byte step1 = ~(byte)254;

but am still getting -255.
Thanks,
Tom

byte step1 = unchecked ((byte)~254);

Works great, thanks! By the way, what does unchecked mean?
Tom

I tells the C# compiler not to behave like a woman and complaining :wink: just joking…

            
byte b = 254;
byte c = (byte)~b;

Should work too.

1 Like