How to convert a string of bits to byte array

后端 未结 7 871
悲&欢浪女
悲&欢浪女 2020-12-06 08:17

I have a string representing bits, such as:

\"0000101000010000\"

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

{0x         


        
7条回答
  •  离开以前
    2020-12-06 08:27

    Use the builtin Convert.ToByte() and read in chunks of 8 chars without reinventing the thing..

    Unless this is something that should teach you about bitwise operations.

    Update:


    Stealing from Adam (and overusing LINQ, probably. This might be too concise and a normal loop might be better, depending on your own (and your coworker's!) preferences):

    public static byte[] GetBytes(string bitString) {
        return Enumerable.Range(0, bitString.Length/8).
            Select(pos => Convert.ToByte(
                bitString.Substring(pos*8, 8),
                2)
            ).ToArray();
    }
    

提交回复
热议问题