Convert.ToString()到二进制格式不能按预期方式工作 [英] Convert.ToString() to binary format not working as expected

查看:71
本文介绍了Convert.ToString()到二进制格式不能按预期方式工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我可以看到二进制输出20可能已被截断,但我不理解-20的输出.我的期望基于base2表示法,再加上一个信念,即整数的有符号元素用最左边的第一个数字表示.0表示正,1表示负.有人可以解释一下结果,特别是-20的结果吗?

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?

推荐答案

.NET中的负数以二进制形式表示为 Two的补语.

Negative numbers in .NET are represented in binary as Two's complement.

从MSDN- Convert.ToString方法(Int32,Int32):

如果value为负并且toBase为2、8或16,则返回的字符串使用二进制补码表示法

If value is negative and toBase is 2, 8, or 16, the returned string uses two's complement representation

这篇关于Convert.ToString()到二进制格式不能按预期方式工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆