0

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;

   }
  • 1
    You might want to call it "integer to binary" since there is a specific `Decimal` type. – ProgrammingLlama Dec 19 '17 at 08:07
  • 1
    Possible duplicate of [easy and fast way to convert an int to binary?](https://stackoverflow.com/questions/1838963/easy-and-fast-way-to-convert-an-int-to-binary) – mjwills Dec 19 '17 at 08:08
  • Possible duplicate of [Decimal to binary conversion in c #](https://stackoverflow.com/questions/2954962/decimal-to-binary-conversion-in-c) – styx Dec 19 '17 at 08:09
  • To add to mjwills comment above: When you ask a question about an exception you encounter, it is always a good idea to include its stacktrace to the question. Makes it easier to analyse the problem and it will be asked for, anyway. – Fildor Dec 19 '17 at 08:33
  • @mjwills I wanted to code it myself, I'm more interested in knowing how it works rather than the output. – Panther_Yens Dec 19 '17 at 10:00

1 Answers1

5

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.

Fildor
  • 14,510
  • 4
  • 35
  • 67