如何将整数转换为二进制表示?
我正在使用下面的代码:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
但是它抛出了一个异常:
找不到任何可解析的数字
如何将整数转换为二进制表示?
我正在使用下面的代码:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
但是它抛出了一个异常:
找不到任何可解析的数字
当前回答
在c#中从任何经典基转换为任何基
string number = "100";
int fromBase = 16;
int toBase = 10;
string result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
// result == "256"
支持的基数是2,8,10和16
其他回答
class Program{
static void Main(string[] args){
try{
int i = (int)Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));
}catch(Exception e){
Console.WriteLine("\n{0}\n",e.Message);
}
}//end Main
public static string ToBinary(Int64 Decimal)
{
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
// The algoritm gives us the binary number in reverse order (mirrored)
// We store it in an array so that we can reverse it back to normal
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}//end class Program
转换。ToInt32(string, base)不会将基数转换为基数。它假设字符串包含一个以指定基数为底的有效数字,并转换为以10为基数。
所以你会得到一个错误,因为“8”不是一个以2为基数的有效数字。
String str = "1111";
String Ans = Convert.ToInt32(str, 2).ToString();
将显示15(1111以2为底= 15以10为底)
String str = "f000";
String Ans = Convert.ToInt32(str, 16).ToString();
将显示61440。
原始的方法:
public string ToBinary(int n)
{
if (n < 2) return n.ToString();
var divisor = n / 2;
var remainder = n % 2;
return ToBinary(divisor) + remainder;
}
这是一个有趣的阅读,我正在寻找一个快速复制粘贴。 我知道我很久以前用bitmath做过这件事。
以下是我的看法。
// i had this as a extension method in a static class (this int inValue);
public static string ToBinaryString(int inValue)
{
string result = "";
for (int bitIndexToTest = 0; bitIndexToTest < 32; bitIndexToTest++)
result += ((inValue & (1 << (bitIndexToTest))) > 0) ? '1' : '0';
return result;
}
你可以在循环中加入一些模数。
// little bit of spacing
if (((bitIndexToTest + 1) % spaceEvery) == 0)
result += ' ';
你可能会使用或传入一个stringbuilder,并直接追加或索引,以避免释放,也可以绕过+=的使用;
如果你想要一个简洁的函数,你可以从你的主方法调用,在你的类中,这可能是有帮助的。如果你需要一个数字而不是字符串,你可能仍然需要调用int.Parse(toBinary(someint)),但我发现这个方法工作得很好。此外,如果您愿意,还可以调整为使用for循环而不是do-while循环。
public static string toBinary(int base10)
{
string binary = "";
do {
binary = (base10 % 2) + binary;
base10 /= 2;
}
while (base10 > 0);
return binary;
}
toBinary(10)返回字符串“1010”。