1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

/* [from office hours]
 * This is a solution to the worksheet from Fri 11/17.
 */

typedef unsigned char uchar;
uchar get_bits(uchar* buf, int start_bit, int end_bit) {
    int start_byte_idx = start_bit / 8;
    int end_byte_idx   = end_bit   / 8;

    uchar ch0 = buf[start_byte_idx];
    int start0          = start_bit % 8;
    int end0            = start_byte_idx == end_byte_idx ? end_bit % 8 : 7;
    int num_bits0       = (end0 - start0 + 1);
    uchar bits0 = (ch0 << start0);
    bits0 = bits0 >> (8 - num_bits0);

    uchar ch1 = buf[end_byte_idx];
    int start1          = 0;
    int end1            = start_byte_idx == end_byte_idx ? 0 : end_bit % 8;
    int num_bits1       = end1 + 1;
    uchar bits1 = (ch1 << start1);
    bits1 = bits1 >> (8 - num_bits1);

    return bits0 << num_bits1 | bits1;
}
int main(int argc, char* argv[]) {
    uchar buf[256] = {255, 127, 63, 31};  // initializes to zero
    /* printf("%d\n", get_bits(buf, 2, 6)); */
    /* assert( get_bits(buf, 2,  6) == 32 - 1 ); */
    printf("%d\n", get_bits(buf, 5, 10));
    assert( get_bits(buf, 5, 10) == 59 );

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2017 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.