Bitmanip
This commit is contained in:
parent
561a344f30
commit
45ef1c4271
1 changed files with 56 additions and 0 deletions
56
bitmanip.c
Normal file
56
bitmanip.c
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
/* Define some bits to represent various flags */
|
||||||
|
#define BIT_USED (1U << 0)
|
||||||
|
#define BIT_FREE (1U << 1)
|
||||||
|
#define BIT_TAINT (1U << 2)
|
||||||
|
#define BIT_DIRTY (1U << 3)
|
||||||
|
|
||||||
|
/* Modifies in-place */
|
||||||
|
#define BIT_SET_NTH(N, K) (N |= (1 << (K - 1)));
|
||||||
|
#define BIT_CLEAR_NTH(N, K) (N &= (~(1 << (K - 1))))
|
||||||
|
#define BIT_TOGGLE_NTH(N, K) (N ^= (1 << (K - 1)))
|
||||||
|
#define BIT_TEST_NTH(N, K) (N & (1 << (K - 1)))
|
||||||
|
|
||||||
|
#define BIT_SET(N, K) (N |= (K))
|
||||||
|
#define BIT_CLEAR(N, K) (N &= ~(K))
|
||||||
|
#define BIT_TOGGLE(N, K) (N ^= (K))
|
||||||
|
#define BIT_TEST(N, K) (N & K)
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
char flags = 0;
|
||||||
|
|
||||||
|
/* Set a set of flags */
|
||||||
|
flags |= BIT_USED | BIT_TAINT;
|
||||||
|
printf("Flags: %.8b\n", flags);
|
||||||
|
|
||||||
|
/* Unset a set of flags */
|
||||||
|
flags &= ~BIT_USED;
|
||||||
|
printf("Flags: %.8b\n", flags);
|
||||||
|
|
||||||
|
/* Toggle a bit */
|
||||||
|
flags ^= BIT_USED;
|
||||||
|
printf("Flags: %.8b\n", flags);
|
||||||
|
|
||||||
|
if (flags & BIT_USED)
|
||||||
|
printf("Bit is used!\n");
|
||||||
|
|
||||||
|
/* Clear all bits except */
|
||||||
|
flags &= BIT_USED;
|
||||||
|
printf("Flags: %.8b\n", flags);
|
||||||
|
|
||||||
|
/* Wipe flags */
|
||||||
|
flags = 0;
|
||||||
|
|
||||||
|
BIT_TOGGLE(flags, BIT_USED);
|
||||||
|
printf("Flags: %.8b\n", flags);
|
||||||
|
|
||||||
|
BIT_SET(flags, BIT_DIRTY | BIT_TAINT);
|
||||||
|
printf("Flags: %.8b\n", flags);
|
||||||
|
|
||||||
|
if (BIT_TEST(flags, BIT_DIRTY))
|
||||||
|
printf("Bit is dirty!\n");
|
||||||
|
|
||||||
|
BIT_CLEAR(flags, BIT_DIRTY | BIT_USED | BIT_TAINT);
|
||||||
|
printf("Flags: %.8b\n", flags);
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue