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
  • 15,684
  • 43
  • 105
  • 161

4 Answers4

22

Try this:

string str = "Hello"; 
byte []arr = System.Text.Encoding.ASCII.GetBytes(str);
A B
  • 1,926
  • 1
  • 20
  • 42
21
string result = string.Empty;
foreach(char ch in yourString)
{
   result += Convert.ToString((int)ch,2);
}

this will translate "Hello" to 10010001100101110110011011001101111

Stecya
  • 22,896
  • 10
  • 72
  • 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
4
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,500
  • 5
  • 51
  • 85