【问题标题】:Convert integer to binary in C#在 C# 中将整数转换为二进制
【发布时间】:2010-06-02 04:11:33
【问题描述】:

如何将整数转换成二进制表示?

我正在使用此代码:

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

但它会抛出异常:

找不到任何可解析的数字

【问题讨论】:

  • 您是要转换数字的字符串表示形式还是实际数字?您是要转换为十进制还是整数?您的示例与您的问题并不完全相符。
  • 如果您希望将十进制转换为字节,您可以使用以下代码:gist.github.com/eranbetzalel/…
  • 您正在尝试将 base-10 字符串解析为 base-2。这就是调用失败的原因。

标签: c#


【解决方案1】:

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

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

返回 1000。

【讨论】:

  • 有没有类似的二进制转十进制的方法?
  • @kashif int value = Convert.ToInt32("1101", 2) 会给 value 值 13。
  • 这是如何工作的? “2”是基数,适用于任何基数吗?
【解决方案2】:

从任何经典基础转换为 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

【讨论】:

  • 这行不通。我只是尝试了string binary = Convert.ToString(533, 26); 并得到了一个 ArgumentException: Invalid base
  • 是的,来自 MSDN:仅支持经典基数 msdn.microsoft.com/en-us/library/8s62fh68(v=vs.110).aspx toBase 类型:System.Int32 返回值的基数,必须是 2、8、10 或 16。
【解决方案3】:

非常简单,无需额外代码,只需输入、转换和输出。

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);
        }
    }
}

【讨论】:

  • 对于通用字母表,应该这样做{ [...] }while(decimalNumber > 0);
  • 如果decimalNumber = 0,结果为空。请更新为 while (decimalNumber > 0 || string.IsNullOrEmpty(result))
【解决方案4】:

http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html

    public string DecimalToBinary(string data)
    {
        string result = string.Empty;
        int rem = 0;
        try
        {
            if (!IsNumeric(data))
                error = "Invalid Value - This is not a numeric value";
            else
            {
                int num = int.Parse(data);
                while (num > 0)
                {
                    rem = num % 2;
                    num = num / 2;
                    result = rem.ToString() + result;
                }
            }
        }
        catch (Exception ex)
        {
            error = ex.Message;
        }
        return result;
    }

【讨论】:

  • 不确定这与 Xenon 的回答有何不同。
  • 他在 Xenon 之前回答了这个问题
【解决方案5】:

原始方式:

public string ToBinary(int n)
{
    if (n < 2) return n.ToString();

    var divisor = n / 2;
    var remainder = n % 2;

    return ToBinary(divisor) + remainder;
}

【讨论】:

  • 因否定而失败,但我还是投了赞成票,因为这是一个有趣的答案。
  • 感谢您的反馈@BrainSlugs83
【解决方案6】:

Convert.ToInt32(string, base) 不会将基础转换为您的基础。它假定字符串包含指定基数的有效数字,并转换为基数 10。

所以你得到一个错误,因为“8”不是以 2 为底的有效数字。

String str = "1111";
String Ans = Convert.ToInt32(str, 2).ToString();

将显示15(1111 base 2 = 15 base 10)

String str = "f000";
String Ans = Convert.ToInt32(str, 16).ToString();

将显示61440

【讨论】:

    【解决方案7】:

    使用EnumerableLINQ 的另一种替代方案也是内联解决方案是:

    int number = 25;
        
    string binary = Enumerable.Range(0, (int)Math.Log(number, 2) + 1).Aggregate(string.Empty, (collected, bitshifts) => ((number >> bitshifts) & 1 ) + collected);
    

    【讨论】:

    • 在这里尝试了许多(但不是全部)非 BCL 答案后,这是我发现的第一个实际有效的答案。他们中的大多数都失败了。
    • 感谢您发现我的代码 :) 但正如您所见,从性能的角度来看,这是个笑话
    • 好吧,我们不能拥有一切,不是吗? ;-)
    • 这个答案让我发笑。在这里投赞成票,你应得的。
    【解决方案8】:
        static void convertToBinary(int n)
        {
            Stack<int> stack = new Stack<int>();
            stack.Push(n);
            // step 1 : Push the element on the stack
            while (n > 1)
            {
                n = n / 2;
                stack.Push(n);
            }
    
            // step 2 : Pop the element and print the value
            foreach(var val in stack)
            {
                Console.Write(val % 2);
            }
         }
    

    【讨论】:

    • 您好!您应该使用您发布的代码添加一些 cmets :)
    • 此函数将在 C# 中将整数转换为二进制。要将整数转换为二进制,我们反复将商除以基数,直到商为零,并记下每一步的余数(使用 Stack.Push 存储值)。然后,我们将余数反向写入,从底部开始,每次都附加到右侧(循环遍历堆栈以打印值)。
    【解决方案9】:

    我知道这个答案看起来与这里的大多数答案相似,但我注意到几乎没有一个使用 for 循环。这段代码可以工作,并且可以被认为是简单的,因为它可以在没有任何特殊函数的情况下工作,比如带有参数的 ToString(),并且也不会太长。也许有些人更喜欢 for 循环而不是 while 循环,这可能适合他们。

    public static string ByteConvert (int num)
    {
        int[] p = new int[8];
        string pa = "";
        for (int ii = 0; ii<= 7;ii = ii +1)
        {
            p[7-ii] = num%2;
            num = num/2;
        }
        for (int ii = 0;ii <= 7; ii = ii + 1)
        {
            pa += p[ii].ToString();
        }
        return pa;
    }
    

    【讨论】:

      【解决方案10】:
      using System;
      
      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);
              }
          }
      
          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;
              }
      
              BinaryArray = BinaryResult.ToCharArray();
              Array.Reverse(BinaryArray);
              BinaryResult = new string(BinaryArray);
      
              return BinaryResult;
          }
      }
      

      【讨论】:

      • 您正在重新发明轮子。 BCL 已经包含执行此操作的方法。
      【解决方案11】:

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

      public static string ToBinary(int N)
      {
          int d = N;
          int q = -1;
          int r = -1;
      
          string binNumber = string.Empty;
          while (q != 1)
          {
              r = d % 2;
              q = d / 2;
              d = q;
              binNumber = r.ToString() + binNumber;
          }
          binNumber = q.ToString() + binNumber;
          return binNumber;
      }
      

      【讨论】:

      • 你应该解释你的代码是如何回答这个问题的。请在发布前阅读 SO 指南。
      • 上面写的代码将无符号整数转换成它的二进制字符串。
      【解决方案12】:
      class Program
      {
          static void Main(string[] args)
          {
              var @decimal = 42;
              var binaryVal = ToBinary(@decimal, 2);
      
              var binary = "101010";
              var decimalVal = ToDecimal(binary, 2);
      
              Console.WriteLine("Binary value of decimal {0} is '{1}'", @decimal, binaryVal);
              Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
              Console.WriteLine();
      
              @decimal = 6;
              binaryVal = ToBinary(@decimal, 3);
      
              binary = "20";
              decimalVal = ToDecimal(binary, 3);
      
              Console.WriteLine("Base3 value of decimal {0} is '{1}'", @decimal, binaryVal);
              Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
              Console.WriteLine();
      
      
              @decimal = 47;
              binaryVal = ToBinary(@decimal, 4);
      
              binary = "233";
              decimalVal = ToDecimal(binary, 4);
      
              Console.WriteLine("Base4 value of decimal {0} is '{1}'", @decimal, binaryVal);
              Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
              Console.WriteLine();
      
              @decimal = 99;
              binaryVal = ToBinary(@decimal, 5);
      
              binary = "344";
              decimalVal = ToDecimal(binary, 5);
      
              Console.WriteLine("Base5 value of decimal {0} is '{1}'", @decimal, binaryVal);
              Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
              Console.WriteLine();
      
              Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
              Console.WriteLine();
      
      
              @decimal = 16;
              binaryVal = ToBinary(@decimal, 11);
      
              binary = "b";
              decimalVal = ToDecimal(binary, 11);
      
              Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
              Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
              Console.WriteLine();
              Console.WriteLine("Uh oh.. this aint right :( ... but let's cheat :P");
              Console.WriteLine();
      
              @decimal = 11;
              binaryVal = Convert.ToString(@decimal, 16);
      
              binary = "b";
              decimalVal = Convert.ToInt32(binary, 16);
      
              Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
              Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
      
              Console.ReadLine();
          }
      
      
          static string ToBinary(decimal number, int @base)
          {
              var round = 0;
              var reverseBinary = string.Empty;
      
              while (number > 0)
              {
                  var remainder = number % @base;
                  reverseBinary += remainder;
      
                  round = (int)(number / @base);
                  number = round;
              }
      
              var binaryArray = reverseBinary.ToCharArray();
              Array.Reverse(binaryArray);
      
              var binary = new string(binaryArray);
              return binary;
          }
      
          static double ToDecimal(string binary, int @base)
          {
              var val = 0d;
      
              if (!binary.All(char.IsNumber))
                  return 0d;
      
              for (int i = 0; i < binary.Length; i++)
              {
                  var @char = Convert.ToDouble(binary[i].ToString());
      
                  var pow = (binary.Length - 1) - i;
                  val += Math.Pow(@base, pow) * @char;
              }
      
              return val;
          }
      }
      

      学习来源:

      Everything you need to know about binary

      including algorithm to convert decimal to binary

      【讨论】:

      • 感谢您演示 ToDecimal() 方法。
      【解决方案13】:
      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
      

      【讨论】:

        【解决方案14】:

        BCL 提供 Convert.ToString(n, 2) 很好,但如果您需要一种替代实现,它比 BCL 提供的快几个滴答。

        以下自定义实现适用于所有整数(-ve 和 +ve)。 原文摘自https://davidsekar.com/algorithms/csharp-program-to-convert-decimal-to-binary

        static string ToBinary(int n)
        {
            int j = 0;
            char[] output = new char[32];
        
            if (n == 0)
                output[j++] = '0';
            else
            {
                int checkBit = 1 << 30;
                bool skipInitialZeros = true;
                // Check the sign bit separately, as 1<<31 will cause
                // +ve integer overflow
                if ((n & int.MinValue) == int.MinValue)
                {
                    output[j++] = '1';
                    skipInitialZeros = false;
                }
        
                for (int i = 0; i < 31; i++, checkBit >>= 1)
                {
                    if ((n & checkBit) == 0)
                    {
                        if (skipInitialZeros)
                            continue;
                        else
                            output[j++] = '0';
                    }
                    else
                    {
                        skipInitialZeros = false;
                        output[j++] = '1';
                    }
                }
            }
        
            return new string(output, 0, j);
        }
        

        以上代码是我的实现。所以,我很想听到任何反馈:)

        【讨论】:

          【解决方案15】:
              // I use this function
              public static string ToBinary(long number)
              {
                  string digit = Convert.ToString(number % 2);
                  if (number >= 2)
                  {
                      long remaining = number / 2;
                      string remainingString = ToBinary(remaining);
                      return remainingString + digit;
                  }
                  return digit;
               }
          

          【讨论】:

            【解决方案16】:
                    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();
                    }           
                }
            

            【讨论】:

            • 我知道代码非常基本,不是太简单,但也可以处理负数
            • 您正在接收 32 位整数,但您的输出数组的大小为 16 位。只是说...
            • 是的,这句话是正确的。对这段代码使用 short 是正确的,但它也适用于 int。这个例子是小数字。如果我们想使用大数,则必须更改类型。这个想法是,如果我们想使用负数,结果应该至少大一个字节,以便程序可以看到这是一个反转的附加代码。
            【解决方案17】:

            如果你想要一个简洁的函数,你可以在你的类中从你的 main 方法调用,这可能会很有帮助。如果您需要数字而不是字符串,您可能仍需要致电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"

            【讨论】:

            • 这与 Govind 的答案几乎相同(令我惊讶的是,这是所有这些答案中唯一等效的从右到左的迭代答案),但你是对的,它更短更整洁。也就是说,我不确定像这样的字符串前置会非常有效,而且无论如何你都不太可能击败内置的效率方法。我也看不出你为什么要再次将其解释为整数,但如果你这样做了,你可以通过以与此类似的方法而不是通过字符串构造 10 的幂来做到这一点。
            【解决方案18】:

            我在编码挑战中遇到了这个问题,您必须将 32 位十进制转换为二进制并找到子字符串的可能组合。

            using System;
            using System.Collections.Generic;
            using System.Globalization;
            using System.Numerics;
            using System.IO;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            
            namespace ConsoleApp2
            {
                class Program
                {
            
                    public static void Main()
                    {
                        int numberofinputs = int.Parse(Console.ReadLine());
                        List<BigInteger> inputdecimal = new List<BigInteger>();
                        List<string> outputBinary = new List<string>();
            
            
                        for (int i = 0; i < numberofinputs; i++)
                        {
                            inputdecimal.Add(BigInteger.Parse(Console.ReadLine(), CultureInfo.InvariantCulture));
                        }
                        //processing begins 
            
                        foreach (var n in inputdecimal)
                        {
                            string binary = (binaryconveter(n));
                            subString(binary, binary.Length);
                        }
            
                        foreach (var item in outputBinary)
                        {
                            Console.WriteLine(item);
                        }
            
                        string binaryconveter(BigInteger n)
                        {
                            int i;
                            StringBuilder output = new StringBuilder();
            
                            for (i = 0; n > 0; i++)
                            {
                                output = output.Append(n % 2);
                                n = n / 2;
                            }
            
                            return output.ToString();
                        }
            
                        void subString(string str, int n)
                        {
                            int zeroodds = 0;
                            int oneodds = 0;
            
                            for (int len = 1; len <= n; len++)
                            {
            
                                for (int i = 0; i <= n - len; i++)
                                {
                                    int j = i + len - 1;
            
                                    string substring = "";
                                    for (int k = i; k <= j; k++)
                                    {
                                        substring = String.Concat(substring, str[k]);
            
                                    }
                                    var resultofstringanalysis = stringanalysis(substring);
                                    if (resultofstringanalysis.Equals("both are odd"))
                                    {
                                        ++zeroodds;
                                        ++oneodds;
                                    }
                                    else if (resultofstringanalysis.Equals("zeroes are odd"))
                                    {
                                        ++zeroodds;
                                    }
                                    else if (resultofstringanalysis.Equals("ones are odd"))
                                    {
                                        ++oneodds;
                                    }
            
                                }
                            }
                            string outputtest = String.Concat(zeroodds.ToString(), ' ', oneodds.ToString());
                            outputBinary.Add(outputtest);
                        }
            
                        string stringanalysis(string str)
                        {
                            int n = str.Length;
            
                            int nofZeros = 0;
                            int nofOnes = 0;
            
                            for (int i = 0; i < n; i++)
                            {
                                if (str[i] == '0')
                                {
                                    ++nofZeros;
                                }
                                if (str[i] == '1')
                                {
                                    ++nofOnes;
                                }
            
                            }
                            if ((nofZeros != 0 && nofZeros % 2 != 0) && (nofOnes != 0 && nofOnes % 2 != 0))
                            {
                                return "both are odd";
                            }
                            else if (nofZeros != 0 && nofZeros % 2 != 0)
                            {
                                return "zeroes are odd";
                            }
                            else if (nofOnes != 0 && nofOnes % 2 != 0)
                            {
                                return "ones are odd";
                            }
                            else
                            {
                                return "nothing";
                            }
            
                        }
                        Console.ReadKey();
                    }
            
                }
            }
            

            【讨论】:

              【解决方案19】:
                  int x=550;
                  string s=" ";
                  string y=" ";
              
                  while (x>0)
                  {
              
                      s += x%2;
                      x=x/2;
                  }
              
              
                  Console.WriteLine(Reverse(s));
              }
              
              public static string Reverse( string s )
              {
                  char[] charArray = s.ToCharArray();
                  Array.Reverse( charArray );
                  return new string( charArray );
              }
              

              【讨论】:

                【解决方案20】:

                这是一本有趣的读物,我正在寻找快速复制粘贴。 我知道我很久以前就以不同的方式使用 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 += ' ';
                

                您可能可以使用或传入字符串生成器并直接附加或索引以避免释放,也可以通过这种方式绕过 += 的使用;

                【讨论】:

                • 你测试你的方法了吗,它给出了反向的二进制字符串
                【解决方案21】:
                var b = Convert.ToString(i,2).PadLeft(32,'0').ToCharArray().Reverse().ToArray();
                

                【讨论】:

                  猜你喜欢
                  • 2021-11-03
                  • 1970-01-01
                  • 2015-05-18
                  • 1970-01-01
                  • 2012-04-10
                  • 2021-09-20
                  • 2018-03-01
                  • 2018-07-07
                  • 2012-05-11
                  相关资源
                  最近更新 更多