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
53
54
55
56
#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.

// Now let's do it with 4-byte unsigned integers (uint32_t)

uint32_t set_bit(uint32_t n, int bit_num_from_left) {  // Longer name reduces ambiguity
    // Suppose we want rhs to be this:
    // 10000000000000000000000000000000
    // ▲
    //
    // Start with this:
    // 00000000000000000000000000000001
    //                                ▲
    // End with this:
    // 10000000000000000000000000000000
    // ▲
    //
    // … and we bitshift that 1 (set bit) left from position 32 to position 1, so 31 places.
    //
    // If we wanted to set bit 2 (from left, 1-based), then bitshift left 30 places.
    //
    // Start with this:
    // 00000000000000000000000000000001
    //                                ▲
    // End with this:
    // 01000000000000000000000000000000
    //  ▲

    return n | 1 << (sizeof(n)*8 - bit_num_from_left);
}

// 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[]) {
    uint32_t n = 0b00000000;

    int bits_to_set[] = {1, 4, 5, 7};
    size_t num_bits = sizeof(bits_to_set) / sizeof(*bits_to_set);  // ONLY WORKS ON REAL ARRAY (declared with ▒[])
    for(int i = 0; i < num_bits; i++) {
        n = set_bit(n, bits_to_set[i]);
    }
    assert(n == 0b10011010000000000000000000000000);

    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.