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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <stdint.h>

// DO NOT COPY THIS CODE INTO YOUR HOMEWORK FILES.  This is the default always. Chance similarity
// is fine, but do not look at this while (or immediately before) doing your own
//
// You cannot use 0b######### syntax in ISO C11.  It is non-standard and used only for this lecture.

uint8_t set_bit(uint8_t n, int bit_num_from_left) {  // Longer name reduces ambiguity
    // STUPID CODE - DO NOT CODE LIKE THIS
    switch(bit_num_from_left) {
        case 1:
            return n | 0b10000000;
        case 2:
            return n | 0b01000000;
        case 3:
            return n | 0b00100000;
        case 4:
            return n | 0b00010000;
        case 5:
            return n | 0b00001000;
        case 6:
            return n | 0b00000100;
        case 7:
            return n | 0b00000010;
        case 8:
            return n | 0b00000001;
        default:
            assert(false);  // shouldn't get here
    }
}
// If I just said bit_num, you might ask if it is from the left or right.  If I tell you, then
// you have to remember.

int main(int argc, char* argv[]) {
    uint8_t n1 = 0b00000000;
    uint8_t n2 = set_bit(n1, 1);  // Set the FIRST bit  
    assert(set_bit(0, 1) == 0b10000000);
    //                        ↑
    assert(set_bit(0, 2) == 0b01000000);
    //                         ↑
    assert(set_bit(0, 8) == 0b00000001);
    //                               ↑
    
    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.