Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the binary code behind ASCII (C#)

Tags:

c#

ascii

binary

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.

like image 901
James Litewski Avatar asked Apr 07 '11 08:04

James Litewski


1 Answers

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));
}
like image 136
Thomas Levesque Avatar answered Oct 13 '22 01:10

Thomas Levesque