Convert a String to binary sequence in C# [duplicate]
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
?
Try this:
string str = "Hello";
byte []arr = System.Text.Encoding.ASCII.GetBytes(str);
string result = string.Empty;
foreach(char ch in yourString)
{
result += Convert.ToString((int)ch,2);
}
this will translate "Hello"
to 10010001100101110110011011001101111
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());
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();
精彩评论