7

Possible Duplicate:
How do you convert a string to ascii to binary in C#?

How to convert string such as "Hello" to Binary sequence as 1011010 ?

Community
  • 1
  • 1
Sudantha
  • 14,804
  • 42
  • 102
  • 158

4 Answers4

22

Try this:

string str = "Hello"; 
byte []arr = System.Text.Encoding.ASCII.GetBytes(str);
Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
A B
  • 1,840
  • 1
  • 19
  • 41
20
string result = string.Empty;
foreach(char ch in yourString)
{
   result += Convert.ToString((int)ch,2);
}

this will translate "Hello" to 10010001100101110110011011001101111

Stecya
  • 22,338
  • 9
  • 70
  • 102
  • 1
    Your string is only 35 characters. You're missing a `.PadLeft(8, '0')` to your `.ToString()` call. – Michael Sep 02 '15 at 17:13
3
string testString = "Hello";
UTF8Encoding encoding = new UTF8Encoding();
byte[] buf = encoding.GetBytes(testString);

StringBuilder binaryStringBuilder = new StringBuilder();
foreach (byte b in buf)
{
    binaryStringBuilder.Append(Convert.ToString(b, 2));
}
Console.WriteLine(binaryStringBuilder.ToString());
0

Use the BitConverter to get the bytes of the string and then format these bytes to their binary representation:

byte[] bytes = System.Text.Encoding.Default.GetBytes( "Hello" );
StringBuilder sb = new StringBuilder();
foreach ( byte b in bytes )
{
    sb.AppendFormat( "{0:B}", b );
}
string binary = sb.ToString();
PVitt
  • 11,142
  • 5
  • 49
  • 84