简体   繁体   中英

how convert sequence of bits in ascii-string c#

How do you convert a string of bits, such as

0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100

to a string of ASCII characters like: "Hello World"?

您需要将它们分成8个字符的字符串(字节),调用Convert.ToByte(str, 2) ,将它们放入byte[] ,然后调用Encoding.ASCII.GetString()

This code example should be clear:

String bits = "01001001000......0001100100"; // shortened here for demo purposes

byte[] bArr = new byte[bits.Length / 8];
for (int i = 0; i < bits.Length / 8; i++)
{
    String part = bits.Substring(i * 8, 8);
    bArr[i] += Convert.ToByte(part, 2);
}
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Console.WriteLine(encoding.GetString(bArr));

Basically split the string in even parts, store the resulting bytes in a byte array and then parse that in a specific encoding.

public string GetBytesFromBinaryString(String binary)
{
    var list = new List<Byte>();

    for (int i = 0; i < binary.Length; i += 8)
    {
        String t = binary.Substring(i, 8);

        list.Add(Convert.ToByte(t, 2));
    }

    return Encoding.ASCII.GetString(list.ToArray());
}

test:

var data = GetBytesFromBinaryString("0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100");

output:

"Hello World"

Use this method

private byte[] GetAsByteArray(string BinaryString)
{
        return Enumerable.Range(0, BinaryString.Length / 8)
            .Select(i => Convert.ToByte(BinaryString.Substring(i * 8, 8), 2)).ToArray();
}

Then call it like

string binaryString = "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100";
string convertedText = System.Text.Encoding.ASCII.GetString(GetAsByteArray(binaryString));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM