代码之家  ›  专栏  ›  技术社区  ›  Thorin Oakenshield

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

c#
  •  141
  • Thorin Oakenshield  · 技术社区  · 15 年前

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

    我使用的代码是:

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

    但它抛出了一个例外:

    找不到任何可分析的数字

    17 回复  |  直到 7 年前
        1
  •  270
  •   Anthony Pegram    15 年前

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

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

    返回1000。

        2
  •  40
  •   Uwe Keim    7 年前

    从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

        3
  •  30
  •   Mark Hall    13 年前

    非常简单,没有额外的代码,只需要输入、转换和输出。

    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);
            }
        }
    }
    
        4
  •  9
  •   wRAR    14 年前

    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;
        }
    
        5
  •  7
  •   Daniel B    9 年前

    原始方式:

    public string ToBinary(int n)
    {
        if (n < 2) return n.ToString();
    
        var divisor = n / 2;
        var remainder = n % 2;
    
        return ToBinary(divisor) + remainder;
    }
    
        6
  •  5
  •   egrunin    15 年前

    Convert.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 .

        7
  •  4
  •   Kaitlyn    11 年前

    我知道这个答案看起来和这里的大多数答案很相似,但我注意到它们中几乎没有一个使用for循环。这段代码可以工作,并且可以被认为是简单的,从某种意义上说,它将在没有任何特殊函数的情况下工作,比如带参数的toString(),并且不会太长。也许有些人更喜欢循环,而不是简单的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;
    }
    
        8
  •  4
  •   Daniel B    7 年前
    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;
        }
    }
    
        9
  •  2
  •   Jeroen    11 年前
    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
    
        10
  •  2
  •   Govind    7 年前

    此函数将在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;
    }
    
        11
  •  2
  •   Daniel B    7 年前
    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

        12
  •  1
  •   trinalbadger587    11 年前
        // 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;
         }
    
        13
  •  1
  •   Kiril Dobrev    8 年前
            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();
            }           
        }
    
        14
  •  1
  •   David Chelliah    8 年前

    提供的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
  •  1
  •   Iona Erofeeff    7 年前

    如果您希望在类内从主方法调用一个简洁的函数,这可能会有所帮助。你可能还需要打电话 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" .

        16
  •  1
  •   Daniel B    7 年前

    另一个可选但也是内联解决方案,使用 Enumerable LINQ 是:

    int number = 25;
    
    string binary = Enumerable.Range(0, (int) Math.Log(number, 2) + 1).Aggregate(string.Empty, (collected, bitshifts) => (number >> bitshifts) % 2 + collected);
    
        17
  •  0
  •   seyed    8 年前
        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 );
    }