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
#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] = {0};  // ⚠ Initialize all bytes to zero.
    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.

    // Write 0100
    set_bit(&buf[0], &pos_bit, 0);
    set_bit(&buf[0], &pos_bit, 1);
    set_bit(&buf[0], &pos_bit, 0);
    set_bit(&buf[0], &pos_bit, 0);

    // Write 100
    set_bit(&buf[0], &pos_bit, 1);
    set_bit(&buf[0], &pos_bit, 0);
    set_bit(&buf[0], &pos_bit, 0);

    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.