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

前端 未结 7 724
说谎
说谎 2021-01-17 10:33
int i = 20;
string output = Convert.ToString(i, 2); // Base2 formatting
i = -20;
output = Convert.ToString(i, 2);
Value   Expected                       


        
7条回答
  •  孤街浪徒
    2021-01-17 11:03

    for integer -20 is 11111111111111111111111111101100 System is using 2's Complement by default. 1's Complement is not ideal for calculation.

    (2's complement is invert of all bit plus one)

    in 2's Complement , which will make 20 + (-20) = 0, can compute math easily without concern positive or negative.

    for example, in signed char : 15 = 00001111, -18 = 2's Complement of (00010010) = 11101101 + 1 = 11101110

    00001111 +11101110 =11111101

    Since first bit is 1, we know it is a negative value. Let's do a reverse 2's Complement.

    11111101 - 1 = 11111100 => -(00000011) it gives -3 which 15 + (-18) = -3

提交回复
热议问题