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 | #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
uint8_t rhs = 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 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.