Convert string to binary sequence in C #

Possible duplicate:
How to convert string in ascii to binary in C #?

How to convert a string such as "Hello"to a binary sequence like 1011010?

+3
source share
4 answers

Try the following:

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

it will translate "Hello"to10010001100101110110011011001101111

+16
source
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());
+2
source

Use the bit converter to get the bytes of the string, and then format these bytes in 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();
0
source

All Articles