5

I'm trying to find out how to convert input to a console, into binary; how can such a conversion be made in C#?
Thank you in advance.

James Litewski
  • 451
  • 2
  • 6
  • 16

3 Answers3

7
string s = Console.ReadLine();
byte[] bytes = Encoding.ASCII.GetBytes(s);

Note that the encoding used by the console isn't actually ASCII... you should probably use Console.InputEncoding instead of Encoding.ASCII

To get the binary representation of each byte, you can use Convert.ToString:

foreach(byte b in bytes)
{
    Console.WriteLine(Convert.ToString(b, 2));
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

An individual character can be implicitly converted to an integer. See the documentation. If you want to convert a whole string then Thomas's suggestion makes more sense.

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
0

You can use .NET's build in BinaryReader/BinaryWriter classes.

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46