Bit flags in C
Setting, clearing, and testing individual bits.
unsigned set_bit(unsigned flags, int pos) {
return flags | (1u << pos);
}
unsigned clear_bit(unsigned flags, int pos) {
return flags & ~(1u << pos);
}
int test_bit(unsigned flags, int pos) {
return (flags >> pos) & 1u;
}
How it works
1u << posbuilds a mask for one bit.|sets,& ~clears that bit.- Shifting then
& 1utests it.
Keywords and builtins used here
clear_bitintreturnset_bittest_bitunsigned
The run, in numbers
- Lines
- 11
- Characters to type
- 222
- Tokens
- 64
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 38 seconds.
Step 1 of 2 in Bit manipulation, step 17 of 20 in Data structures & algorithms.