int i = 20;
string output = Convert.ToString(i, 2); // Base2 formatting
i = -20;
output = Convert.ToString(i, 2);
Value Expected Actual 20 00000000000000000000000000010100 10100 -20 10000000000000000000000000010100 11111111111111111111111111101100
I can see that perhaps the binary output of 20 has been truncated but I do not understand the output for -20. I based my expectations on base2 notation plus a belief that the signed element of an integer was expressed in the first left most digit. 0 for positive and 1 for negative. Can someone explain the results, specifically that of -20?
Negative numbers in .NET are represented in binary as Two's complement.
From MSDN - Convert.ToString Method (Int32, Int32):
If value is negative and toBase is 2, 8, or 16, the returned string uses two's complement representation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With