C #에서 정수를 이진수로 변환


192

정수를 이진 표현으로 변환하는 방법은 무엇입니까?

이 코드를 사용하고 있습니다 :

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

그러나 예외가 발생합니다.

구문 분석 가능한 숫자를 찾을 수 없습니다


1
숫자 또는 실제 숫자의 문자열 표현을 변환하려고합니까? 그리고 십진수 또는 정수로 변환하려고합니까? 귀하의 예가 실제로 귀하의 질문과 일치하지 않습니다.
womp

십진수를 바이트로 변환하려는 경우 다음 코드를 사용할 수 있습니다. gist.github.com/eranbetzalel/…
Eran Betzalel

base-10 문자열을 base-2로 구문 분석하려고합니다. 그래서 전화가 실패합니다.
RJ Dunnill

답변:


364

예제에는 문자열로 표현 된 정수가 있습니다. 정수가 실제로 정수라고 가정하면 정수를 가져 와서 이진 문자열로 변환하려고합니다.

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

1000을 반환합니다.


이진수를 십진수로 변환하는 비슷한 방법이 있습니까?
카 시프

30
@kashif int value = Convert.ToInt32("1101", 2)value값 13을 줄 것입니다.
flindeberg

45

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입니다.


1
작동하지 않습니다. 나는 단순히 시도 string binary = Convert.ToString(533, 26);하고 ArgumentException이있어 : 잘못된 기본
매그넘

5
그러나 MSDN의 경우 : 기본 기반 만 지원됩니다. msdn.microsoft.com/en-us/library/8s62fh68(v=vs.110).aspx toBase 형식 : System.Int32 반환 값의 기준은 2 여야합니다. 8, 10 또는 16.
sritmak

37

추가 코드없이 입력, 변환 및 출력만으로 매우 간단합니다.

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

1
일반 알파벳의 경우이 작업을 수행해야합니다 {[...]} while (decimalNumber> 0);
Stefan Steiger

decimalNumber = 0 인 경우 결과는 비어 있습니다. 제발 동안 (decimalNumber> 0 || string.IsNullOrEmpty (결과))으로 업데이트
akkapolk

13

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

2
이것이 크세논의 대답과 어떻게 다른지 확실하지 않습니다.
Joshua Drake

5
그는 제논 전에 대답
레자 Taibur에게

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

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합니다.


4

나는이 답변이 이미 여기에있는 대부분의 답변과 비슷하다는 것을 알고 있지만 그중 어느 것도 for-loop를 사용하지 않는다는 것을 알았습니다. 이 코드는 매개 변수가있는 ToString ()과 같은 특수 함수없이 작동하며 너무 길지 않다는 점에서 간단하게 간주 될 수 있습니다. 어쩌면 일부는 while 루프 대신 for 루프를 선호 할 수도 있습니다.

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

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

6
여기서 바퀴를 재발 명하고 있습니다. BCL에는 이미이를 수행하는 메소드가 포함되어 있습니다.
Eltariel

4

및를 사용하는 또 다른 대안이지만 인라인 솔루션 은 다음 EnumerableLINQ같습니다.

int number = 25;

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

1
여기에 BCL이 아닌 많은 답변을 모두 시도한 후 실제로 작동하는 첫 번째 답변입니다. 그들 대부분은 훌륭하게 실패합니다.
InteXX

1
내 코드를 발견 주셔서 감사합니다 :)하지만 당신이 볼, 그것은보기의 성능 지점에서 농담입니다
Sanan Fataliyev

글쎄, 우리는 모든 것을 가질 수 없습니다. ;-)
InteXX

3

이 함수는 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;
}

3
코드가 질문에 어떻게 대답하는지 설명해야합니다. 게시하기 전에 SO 지침을 읽으십시오.
sparkplug

위의 코드는 부호없는 정수를 이진 문자열로 변환합니다.
Govind

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

학습 소스 :

바이너리에 대해 알아야 할 모든 것

십진수를 이진수로 변환하는 알고리즘 포함


ToDecimal () 메소드를 시연 해 주셔서 감사합니다.
Rajiv

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

1
여보세요 ! 당신은 당신이 게시 한 코드로 주석을 추가해야합니다 :)
toshiro92

이 함수는 C #에서 정수를 이진수로 변환합니다. 정수를 이진수로 변환하기 위해 몫이 0이 될 때까지 몫을 반복해서 밑으로 나눕니다. 각 단계에서 나머지를 기록합니다 (값 저장을 위해 Stack.Push 사용). 그런 다음 나머지를 역순으로 작성합니다. 맨 아래부터 시작하여 매번 오른쪽에 추가합니다 (값을 인쇄하기 위해 스택을 통해 루프).
rahul sharma

2
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

2

제공된 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);
}

위의 코드는 내 구현입니다. 그래서, 나는 의견을 듣고 싶어합니다 :)


1
    // 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;
     }

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

1
나는 코드가 매우 기본적이지 않고 너무 단순하지는 않지만 음수로도 작동한다는 것을 알고있다
Kiril Dobrev

32 비트 정수를 받고 있지만 출력 배열의 크기는 16 비트입니다. 그냥 말하기
David Chelliah

1
예, 말이 맞습니다. 이 코드를 짧게 사용하는 것이 좋지만 int와 함께 작동합니다. 예는 작은 숫자입니다. 큰 숫자를 사용하려면 유형을 변경해야합니다. 우리가 음수로 작업하려면 결과가 최소 1 바이트 더 커야 프로그램이 이것이 반전 된 추가 코드임을 알 수 있습니다.
Kiril Dobrev

1

클래스 내부의 기본 메소드에서 호출 할 수있는 간결한 함수를 원할 때 도움이 될 수 있습니다. 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의 거듭 제곱으로 출력을 구성하여 그렇게 할 수 있습니다.
Rup

1

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

    }
}

0
    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 );
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.