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.
Asked
Active
Viewed 1.5k times
5

James Litewski
- 451
- 2
- 6
- 16
-
Can you be more specific? It is not clear what you want to ask. Give an example if possible. – Stephen Chung Apr 07 '11 at 08:39
-
Say someone enters the letter 'a' when the console hits a ReadLine() How could I convert that 'a' into binary code? – James Litewski Apr 07 '11 at 08:41
-
It's still unclear. What does 'a' mean in binary? Does it mean 97 or 10? – prostynick Apr 07 '11 at 08:43
-
How is it unclear? The Binary code, Base2. – James Litewski Apr 07 '11 at 08:44
-
You want the ASCII code of that character, into an integer variable? Just type cast it into an int. E.g. `int code = (int) ch;` – Stephen Chung Apr 07 '11 at 08:46
-
everything is binary, the rest is just an illusion. ;) now, what exactly do you want to do with that 'binary' data? write it somewhere? – Marius Bancila Apr 07 '11 at 08:47
-
I just need to know how to get the binary code, I know how to write it somewhere. – James Litewski Apr 07 '11 at 08:50
-
Simple question: if user inputs 'a' what binary code/number you are expecting to have? – prostynick Apr 07 '11 at 08:54
-
Okay, I don't know binary myself, so I had to use an online converter.. Anyway, I'm guessing it gave me the correct answer; if the user inputs 'a' the output would be '01100001' – James Litewski Apr 07 '11 at 08:57
3 Answers
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
-
-
-
@James Litewski, isn't it what you want? If not, you should probably clarify the question... – Thomas Levesque Apr 07 '11 at 09:01
-
Oh, I get it... you want the binary representation of the ASCII value, right ? – Thomas Levesque Apr 07 '11 at 09:02
-
-
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