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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef unsigned char uchar;
uchar get_bit(uchar ch, int bit_idx) {
return ch >> (7 - bit_idx) & 1;
}
uchar set_bit(uchar ch, int bit_idx, uchar new_value) {
if(new_value) { // bit_idx==2
// Set bit (to 1) // ↓
return ch | (1 << (7 - bit_idx)); // bitwise-or with a byte like this: 00100000
}
else {
// Unset bit (to 0) // bit_idx==2
assert(new_value == 0); // ↓
return ch & (~ (1 << (7 - bit_idx))); // bitwise-and with a byte like this: 11011111
}
}
int main(int argc, char* argv[]) {
assert( get_bit(0xcb, 1) == 1 );
assert( set_bit(0x00, 0, 1) == 0x80 ); // 10000000₂
assert( set_bit(0xcb, 2, 1) == 0xeb ); // 0xcb == 11001011₂, 0xeb == 11101011₂
assert( set_bit(0xeb, 2, 0) == 0xcb ); // 0xcb == 11001011₂, 0xeb == 11101011₂
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2022 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.