How to convert a string of bits to byte array

2019-01-15 03:38发布

I have a string representing bits, such as:

"0000101000010000"

I want to convert it to get an array of bytes such as:

{0x0A, 0x10}

The number of bytes is variable but there will always be padding to form 8 bits per byte (so 1010 becomes 000010101).

标签: c# .net parsing
7条回答
你好瞎i
2楼-- · 2019-01-15 04:13
private static byte[] GetBytes(string bitString)
{
    byte[] result = Enumerable.Range(0, bitString.Length / 8).
        Select(pos => Convert.ToByte(
            bitString.Substring(pos * 8, 8),
            2)
        ).ToArray();

    List<byte> mahByteArray = new List<byte>();
    for (int i = result.Length - 1; i >= 0; i--)
    {
        mahByteArray.Add(result[i]);
    }

    return mahByteArray.ToArray();
}

private static String ToBitString(BitArray bits)
{
    var sb = new StringBuilder();

    for (int i = bits.Count - 1; i >= 0; i--)
    {
        char c = bits[i] ? '1' : '0';
        sb.Append(c);
    }

    return sb.ToString();
}
查看更多
登录 后发表回答