แปลงจำนวนเต็มเป็นเลขฐานสองใน C #


192

วิธีการแปลงจำนวนเต็มเป็นตัวแทนไบนารี?

ฉันใช้รหัสนี้:

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

แต่มันมีข้อยกเว้น:

ไม่พบตัวเลขที่แยกวิเคราะห์ได้


1
คุณพยายามแปลงการแทนค่าสตริงของตัวเลขหรือจำนวนจริงหรือไม่? และคุณพยายามแปลงเป็นทศนิยมหรือ int? ตัวอย่างของคุณไม่ตรงกับคำถามของคุณ
womp

หากคุณต้องการแปลงทศนิยมเป็นไบต์คุณสามารถใช้รหัสนี้: gist.github.com/eranbetzalel/ …
Eran Betzalel

คุณกำลังพยายามแยกสตริงฐาน 10 เป็นฐาน 2 นั่นเป็นสาเหตุที่การโทรล้มเหลว
RJ Dunnill

คำตอบ:


364

ตัวอย่างของคุณมีจำนวนเต็มแสดงเป็นสตริง สมมติว่าจำนวนเต็มของคุณเป็นจำนวนเต็มจริง ๆ แล้วคุณต้องการที่จะนำจำนวนเต็มมาแปลงเป็นสตริงเลขฐานสอง

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

ซึ่งส่งคืน 1,000


มีวิธีใดที่คล้ายกันในการแปลงเลขฐานสองเป็นทศนิยม
kashif

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);และได้รับข้อยกเว้น: ฐานไม่ถูกต้อง
Magnum

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
สำหรับตัวอักษรทั่วไปควรทำ {[... ]} ในขณะที่ (ฐานสิบ> 0);
Stefan Steiger

ในกรณีที่เป็นเลขฐานสิบ = 0 ผลลัพธ์จะว่างเปล่า โปรดอัปเดตเป็นในขณะที่ (จำนวนทศนิยม> 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
ไม่แน่ใจว่าสิ่งนี้แตกต่างจากคำตอบของ Xenon อย่างไร
Joshua Drake

5
เขาตอบคำถามนี้ก่อน Xenon
Reza 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 ฐาน 2 = 15 ฐาน 10)

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

61440จะแสดง


4

ฉันรู้ว่าคำตอบนี้จะคล้ายกับคำตอบส่วนใหญ่ที่นี่แล้ว แต่ฉันสังเกตเห็นว่าไม่มีใครใช้ for-loop รหัสนี้ใช้งานได้และถือได้ว่าเรียบง่ายในแง่ที่ว่ามันจะทำงานโดยไม่มีฟังก์ชั่นพิเศษใด ๆ เช่น ToString () พร้อมพารามิเตอร์และไม่ยาวเกินไป บางทีบางคนอาจชอบวงวนแทนห่วงสักครู่นี่อาจเหมาะกับพวกเขา

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

ทางเลือกอื่น แต่ยังใช้วิธีแก้ปัญหาแบบอินไลน์EnumerableและLINQคือ:

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 # ในการแปลงจำนวนเต็มเป็น Binary เราจะทำการหารผลหารฐานโดยหารซ้ำจนกระทั่งหารเป็นศูนย์จดบันทึกเศษที่เหลือในแต่ละขั้นตอน (ใช้ Stack.Push เพื่อเก็บค่า) จากนั้นเราเขียนส่วนที่เหลือในสิ่งที่ตรงกันข้ามเริ่มต้นที่ด้านล่างและผนวกไปทางขวาในแต่ละครั้ง (วนรอบสแต็คเพื่อพิมพ์ค่า)
ราหุลชาร์

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 เช่นกัน ตัวอย่างมีจำนวนน้อย หากเราต้องการใช้จำนวนมากประเภทจะต้องเปลี่ยน แนวคิดคือถ้าเราต้องการทำงานกับตัวเลขลบผลลัพธ์ควรมีขนาดใหญ่กว่าอย่างน้อยหนึ่งไบต์ดังนั้นโปรแกรมสามารถเห็นได้ว่านี่เป็นรหัสเพิ่มเติมแบบกลับด้าน
คิริล 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 ในวิธีที่คล้ายกันแทนที่จะเป็นทางสตริง
เปียห์

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.