如何将整数转换为二进制表示?
我正在使用下面的代码:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
但是它抛出了一个异常:
找不到任何可解析的数字
如何将整数转换为二进制表示?
我正在使用下面的代码:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
但是它抛出了一个异常:
找不到任何可解析的数字
当前回答
这是一个有趣的阅读,我正在寻找一个快速复制粘贴。 我知道我很久以前用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,并直接追加或索引,以避免释放,也可以绕过+=的使用;
其他回答
这是一个有趣的阅读,我正在寻找一个快速复制粘贴。 我知道我很久以前用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,并直接追加或索引,以避免释放,也可以绕过+=的使用;
转换。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。
您的示例中有一个表示为字符串的整数。假设你的整数实际上是一个整数,你想把这个整数转换成二进制字符串。
int value = 8;
string binary = Convert.ToString(value, 2);
返回1000。
非常简单,没有额外的代码,只是输入,转换和输出。
using System;
namespace _01.Decimal_to_Binary
{
class DecimalToBinary
{
static void Main(string[] args)
{
Console.Write("Decimal: ");
int decimalNumber = int.Parse(Console.ReadLine());
int remainder;
string result = string.Empty;
while (decimalNumber > 0)
{
remainder = decimalNumber % 2;
decimalNumber /= 2;
result = remainder.ToString() + result;
}
Console.WriteLine("Binary: {0}",result);
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter number for converting to binary numerical system!");
int num = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[16];
//for positive integers
if (num > 0)
{
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
Console.Write(arr[y]);
}
Console.ReadLine();
}
//for negative integers
else if (num < 0)
{
num = (num + 1) * -1;
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
if (arr[y] != 0)
{
arr[y] = 0;
}
else
{
arr[y] = 1;
}
Console.Write(arr[y]);
}
Console.ReadLine();
}
}