Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
258 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...