简体   繁体   中英

Converting Decimal to Binary C# using functions

I want to make a converter for decimal to binary using a function but I don't see what is wrong with my code: (the errors states that i can not simplicity convert string to char but I have converted it in line 12). Edit - I am interested in the process of converting denary to binary rather than the output.

    static void Main (string[] args)
    {
     Console.WriteLine("Decimal 14 = Binary " + dec_to_bin(14));
     Console.WriteLine("Decimal 100 = Binary " + dec_to_bin(100));
     Console.WriteLine("Decimal 32 = Binary " + dec_to_bin(32));
     Console.WriteLine("Decimal 64 = Binary " + dec_to_bin(64));
     Console.ReadLine();
    }
    public static string dec_to_bin(int dec)
    {
     string binary = "11111111";
     char[]binaryArray = binary.ToCharArray();

     for (int i = 0; i < 8; i++)
     {
      if (dec % 2 == 0)
      {
       binaryArray[i] = "0"; // error 1
      }
      else 
      {
       binaryArray[i] = "1"; // error 2
      }
     }

     binary = new string(binaryArray);
     return binary;

   }

binaryArray[i] = "0" must be binaryArray[i] = '0'

"0" is a string literal while '0' is a char and you have an array of char .

Same for binaryArray[i] = "1"


While the above will solve your problem, I recommend using Convert.ToString(dec, 2) (as suggested by the dupe marked by mjwills). Of course, this makes only sense if you are interested in the outcome rather than in coding it yourself.


Mind that I deliberately did not address any other issues with the code snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM