Aussie AI
Bit Flag Basics
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Bit Flag Basics
The main use of C++ bitwise operators is to use bit flags in integer variables,
which is very efficient in both storage space and execution time.
A vanilla “int
” can store 32 bit flags,
and a “long
” can store 64 bits.
The basic bit operations in C++ use these bitwise operators:
- Check a bit — bitwise-AND (
&
) - Set a bit — bitwise-OR (
|
) - Toggle a bit — bitwise-XOR (
^
) - Clear a bit — bitwise-AND with complement (
&
with~
)
Here are some example macros for examining the bits in a 32-bit integer,
which should be of “unsigned int
” type:
// Bit Flags in Integers #define AUSSIE_ONE_BIT_SET(x, b) \ (( ((unsigned)(x)) & ((unsigned)(b))) != 0 ) #define AUSSIE_ANY_BITS_SET(x, b) \ (( ((unsigned)(x)) & ((unsigned)(b))) != 0 ) #define AUSSIE_ALL_BITS_SET(x, b) \ ((((unsigned)(x))&((unsigned)(b))) == ((unsigned)(b))) #define AUSSIE_NO_BITS_SET(x, b) \ (( ((unsigned)(x)) & ((unsigned)(b))) == 0 )
The corresponding macros to set and clear these bit flags are:
#define AUSSIE_SET_BITS(x, b) \ (( ((unsigned)(x)) | ((unsigned)(b)))) #define AUSSIE_CLEAR_BITS(x, b) \ (( ((unsigned)(x)) & (~((unsigned)(b))))) #define AUSSIE_TOGGLE_BITS(x, b) \ (( ((unsigned)(x)) ^ ((unsigned)(b))))
Yikes! What a mess! But all those parentheses are necessary to avoid precedence issues with preprocessor macros.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |