2

I have a byte array of length 64. I have a sequential list of what the data in this byte array corresponds to. This list tells me the size in bits that each value is. Most values are 8 or 16 bits which is easy enougth to parse out. However, about mid way through the list i start getting length of 12 bits or 5 bits. What is the best way to loop through these and pull out the bits i need.

2
  • Do you have a byte array with data and want to split it in 5/8/12/16 bit chunks according to another array? Split to an array of ushort/uint? Or what? Commented Apr 8, 2012 at 5:29
  • @erikH - the size of number of bits is different in the 2 files i'm looking at, but they are defined in the header. This header is then followed by the data. To read the data i can look at the head and walk through it by referencing the hearder info, if that makes sense. Anyways just trying to figure out the best approach to tackle this in c#. Commented Apr 9, 2012 at 15:35

1 Answer 1

1

The following code should extract n bits from a data buffer stored as a uint[]. I haven't tested it, so caveat lector.

uint GetBits(uint[] data, ref uint pos, uint n) {
    uint a = pos/32;
    uint off = pos%32;
    uint mask = (1 << n) - 1;
    pos += n;
    return (data[a] << off)&mask | (data[a + 1] >> (32 - off))&mask;
}

Note that it assumes little-endian storage, so that unaligned values flow from the high bits of one word into the low bits of the next.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.