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
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <stdint.h>

void print_byte(uint8_t byte) {
    for(int pos = 0; pos < 8; pos++) {
        int bit_value = (byte >> (8 - 1 - pos)) & 1;    // 001
        char ch = '0' + bit_value;
        fputc(ch, stdout);
    }
}

void set_bit(uint8_t* a_buf_byte, int* a_pos_bit, int bit_value) {
    a_buf_byte |= bit_value << (8 - 1 - *a_pos_bit);
    *a_pos_bit += 1;
}

int main(int argc, char* argv[]) {
    uint8_t buf[8];
    int pos_bytes = 0;
    int pos_bit   = 0;  // 0 is most-significant (128's place), 7 is least significant (1's place)
    
    // Write 0100 100 00 00 110 1011 1110 011 00 0101 100 00 00 1111 011 110 1011 1110 1010 011 110.
    //
    // Step 1:  Write 0100 to an empty buffer.
    //   ∙ 1a:  Write 0 to an empty buffer.  (nothing to do)
    pos_bit += 1;
    //   ∙ 1b:  Write 1 to position 1 (2nd bit)
    //          Byte 0 starts as 00000000₂ and want to get 01000000₂.
    buf[0] = 1 << (8 - 1 - pos_bit);  // can use = because the byte is empty
    pos_bit += 1;
    //   ∙ 1c:  Write 0 to position 2 (3nd bit) - nothing to do
    pos_bit += 1;
    //   ∙ 1d:  Write 0 to position 3 (4th bit) - nothing to do
    pos_bit += 1;
    
    // Step 2:  Write 100 to an empty buffer.
    //   ∙ 2a:  Write 1 to position 4 (5th bit)
    buf[0] |= 1 << (8 - 1 - pos_bit);  // can use = because the byte is empty
    pos_bit += 1;
    //   ∙ 2b:  Write 0 to position 5 (6th bit)
    pos_bit += (8 - 1 - pos_bit);
    //   ∙ 2c:  Write 0 to position 6 (7th bit)
    pos_bit += (8 - 1 - pos_bit);

    print_byte(buf[0]); // 01001000  ←  this is correct

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

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