在C#中将整数转换为二进制

在C#中将整数转换为二进制

问题描述:

如何将整数转换为二进制表示形式?

How to convert an integer number into its binary representation?

我正在使用以下代码:

String input = "8";
String output = Convert.ToInt32(input, 2).ToString();

但是它引发了一个例外:

But it throws an exception:


找不到任何可分析的数字

Could not find any parsable digits


您的示例有一个表示为字符串的整数。假设您的整数实际上是一个整数,并且您想要将该整数转换为二进制字符串。

Your example has an integer expressed as a string. Let's say your integer was actually an integer, and you want to take the integer and convert it to a binary string.

int value = 8;
string binary = Convert.ToString(value, 2);

返回1000。