Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToString() to binary format not working as expected

Tags:

c#

binary

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?

like image 740
FuzzyFrog Avatar asked Jul 22 '11 13:07

FuzzyFrog


1 Answers

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

like image 183
Oded Avatar answered Sep 18 '22 06:09

Oded