开发者

Convert a String to binary sequence in C# [duplicate]

This question already has answers here: Closed 11 years ago. 开发者_开发问答

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜