Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Extract bits from byte stream
#include <stdio.h>
#include <stdlib.h>
/*
Starting at position <position> extract <length> older bits.
Example:
bit number:
7 6 5 4 3 2 1 0 | 15 14 13 12 11 10 9 8 | 23 22 21 20 19 18 17 16
----------
bit value:
1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0
For the above sol(stream, 5, 3) should return 1100 and sol(stream, 0, 2) should
return 001
*/
unsigned int sol(unsigned char *stream,
unsigned position,
unsigned length)
{
static const unsigned masks[8] = {1, 3, 7, 15, 31, 63, 127, 255};
unsigned int result = stream[position / 8];
result = result >> (position % 8);
if ((position + length) / 8 > (position / 8))
{
result = result | (stream[position / 8 + 1] << 8 -
(position % 8));
}
result = result & masks[length];
return result;
}
int main(void)
{
int i1 = 8421761;
printf("%u\n", sol((unsigned char *) &i1, 5, 3));
printf("%u\n", sol((unsigned char *) &i1, 2, 6));
printf("%u\n", sol((unsigned char *) &i1, 0, 2));
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment