如何整数转换在C#中的二进制字符串? [英] How to convert integer to binary string in C#?
问题描述
我在写一个数字转换器。我怎么能一个整数转换为C#中的二进制字符串,不使用内置函数( Convert.ToString
确实根据给定的值不同的东西)?
I'm writing a number converter. How can I convert a integer to a binary string in C# WITHOUT using built-in functions (Convert.ToString
does different things based on the value given)?
- 二进制 - >登录幅度
- 二进制 - >一补
- 二进制>双补
推荐答案
几乎所有的电脑目前使用的补再presentation内部,所以,如果你做一个简单的转换这样,你会得到的二进制补码字符串:
Almost all computers today use two's complement representation internally, so if you do a straightforward conversion like this, you'll get the two's complement string:
public string Convert(int x) {
char[] bits = new char[32];
int i = 0;
while (x != 0) {
bits[i++] = (x & 1) == 1 ? '1' : '0';
x >>= 1;
}
Array.Reverse(bits, 0, i);
return new string(bits);
}
这是你余下的两次转换的基础。对于符号 - 幅度,只需事先提取的符号和转换的绝对值:
That's your basis for the remaining two conversions. For sign-magnitude, simply extract the sign beforehand and convert the absolute value:
byte sign;
if (x < 0) {
sign = '1';
x = -x;
} else {
sign = '0';
}
string magnitude = Convert(x);
有关的补,减之一,如果该数字为负:
For one's complement, subtract one if the number is negative:
if (x < 0)
x--;
string onec = Convert(x);
这篇关于如何整数转换在C#中的二进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!