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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef unsigned char uchar;
uchar get_bit(uchar byte, int bit_idx) {
uchar bit = byte << bit_idx;
return bit >> 7;
}
uchar set_bit(uchar byte, int bit_idx, uchar new_bit) {
if(new_bit == 1) {
return byte | 1 << (7 - bit_idx);
}
else {
return byte & ~(1 << (7 - bit_idx));
}
}
uchar set_bit(uchar byte, int bit_idx, uchar new_bit) {
assert(new_bit == 0 || new_bit == 1);
return (new_bit == 1 ? byte | 1 << (7 - bit_idx) : byte & ~(1 << (7 - bit_idx)));
}
int main(int argc, char* argv[]) {
uchar byte = 0x2f; // 00101111
// △
// idx=4
int idx = 4;
//int bit = (byte << idx) >> 7;
// internally
uchar bit = (byte << idx); // 00000…01011100000
bit = bit >> 7;
printf("bit == %d\n", bit);
printf("set_bit(0x00101111, 3, 1) == 0x%02x\n", set_bit(0x2f, 3, 1));
assert(set_bit(0x2f, 3, 1) == 0x3f);
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2024 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.