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 <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
// uint8_t rhs = 0b10000000 >> bit_num_from_left;
// // WATCH OUT!!! You need -1 if bit_num_from_left is 1-based
// Long form
//uint8_t rhs = 0b10000000 >> (bit_num_from_left - 1);
//return n | rhs;
// Now all together:
return n | 0b10000000 >> (bit_num_from_left - 1);
}
// 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 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 == 0b10011010);
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.