wsh8z
wsh8z

Reputation: 29

How to extract bytes from a byte array starting at a bit position not on a byte boundary c#

I have a byte array in c#. I need to pull out a certain number of bytes starting at a bit position that may not lie on a byte boundary.

Upvotes: 0

Views: 645

Answers (2)

Martin
Martin

Reputation: 1048

Write a little helper method which uses the shift operators to get a byte out e.g.

byte[] x = new[] {0x0F, 0xF0}
result = x[0] << 4 | x[1] >> 4;

returns 8 bits from the 5th bit position 0xFF

You could easily vary the position using the modulo operator %

Upvotes: 1

pfries
pfries

Reputation: 1758

a byte is the minimal alignment you can read with the standard stream readers in .NET

If you want to read bits, you need to use bitwise operators and masks to determine if a bit is on (1) or off (0).

But, this means you could use boolean true/false to tell what the contents of a byte are. One way is to read the bits into a boolean enumeration. Something like this extension method could work:

public static IEnumerable<bool> BitsToBools(IEnumerable<byte> input)
{
    int readByte;
    while((readByte = input.MoveNext()) >= 0)
    {
        for(int i = 7; i >= 0; i--) // read left to right
            yield return ((readByte >> i) & 1) == 1;
    }
}

You could add a startIndex and a count to the extension method if you want, or pass in the range from the calling method.

Upvotes: 0

Related Questions