1

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 "

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Pobaranchuk
  • 839
  • 9
  • 13

1 Answers1

2

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.

Henrik Clausen
  • 679
  • 6
  • 16