Created
September 30, 2015 13:20
-
-
Save ardrabczyk/aaf2517f1262418b3c9f to your computer and use it in GitHub Desktop.
Extract bits from byte stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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