Why [1111 1111] represents as -1 but not 255 in Integer?

274 Views Asked by At

I do a number sign replacement according to the rule: invert bit by bit, and add 1, but I work with an integer data type not sbyte. How does the compiler understand that I am changing the sign,

enter image description here

and not returning the value 255?

        int operand1 = 0, operand2 = 0;
        int result;

        operand1 = 0x01;                            // [0000 0001]
        result = ~operand1;                         // [1111 1110]
        result++;                                   // [1111 1111]

        Console.WriteLine(" ~ {0} + 1 = {1} ", operand1, result);

output: " ~ 1 + 1 = -1 "

1

There are 1 best solutions below

0
Henrik Clausen On BEST ANSWER

There are signed and unsigned integers. The signed integers can hold negative values and as such the "upper" portion of the range counts from (0- (int.max / 2)) and down.

See this article : https://en.wikipedia.org/wiki/Two%27s_complement

if you use an Unsigned int, it behaves as I think you'd expect.

In signed ints the highest bit determines if its a negative value.