I am trying to understand the following:
int 19 in binary is 10011 uint 19 in binary is 10011
so when I do the ~ operation on the int 19 it becomes -20
~19 int in binary is 11111111111111111111111111101100 ~19 uint in binary is 11111111111111111111111111101100
But if I output this, the int ~19 becomes -20 and the uint ~19 becomes 4294967276
I mean how does this work in terms of ones and zeros? How does It know which is the minus sign in int and uint?
CodePudding user response:
There is no minus sign in uint
cause it is literally unsigned 32-bit integer. As for the int
- first bit is responsible for sign of the number (0
is positive, 1
is negative). Both numbers in the binary form have the same representation:
int x = 19;
uint y = 19;
Console.WriteLine(Convert.ToString(~x, toBase: 2)); // prints 11111111111111111111111111101100
Console.WriteLine(Convert.ToString(unchecked((int)~y), toBase: 2)); // also prints 11111111111111111111111111101100
CodePudding user response:
A type of a variable stores information about its representation (and therefore, its interpretation). If the type is int
, the program will know how to interpret whatever is stored in memory for that int
.
When you do 1's complement of (19)10, you get:
(0000 0000 0000 0000 0000 0000 0001 0011)2 = (19)10
(1111 1111 1111 1111 1111 1111 1110 1100)2 = ~(19)10
In C#, 2's complement is used for int
representation, which means that the most significant bit will represent the sign of a variable (1 is negative), and the value is calculated by complementing each bit and adding 1 (more on Two's complement):
(1111 1111 1111 1111 1111 1111 1110 1100)2 -> in the memory location for an
int
(0000 0000 0000 0000 0000 0000 0001 0011)2 -> complement of whatever is in memory for thatint
1
= (0000 0000 0000 0000 0000 0000 0001 0100)2 = (20)10
Therefore giving us the -20
in the int
variable.
As for the uint
variable, there's no sign, no 2's complement, so the whole 32 bits are used for the value.
(1111 1111 1111 1111 1111 1111 1110 1100)2 = ~(19)10 = (4 294 967 276)10