Main Site Documentation

Problem - Negative number when Inverting Integer using the ~ operator


#1

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


#2

Try inverting “unsigned integer”.

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


#3

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

byte step1 = ~(byte)254;

but am still getting -255.
Thanks,
Tom


#4

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


#5

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


#6

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


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

Should work too.