I often have the situation where I need several constants generated at compile time for the use of bit shift and masking operations.
e.g.
#define blockbits 8
#define blocksize 256 // could be generated from 2^blockbits
#define blocksize 0xFF // could be generated from blocksize - 1
I would like all these to be generated from blockbits
, however there is no power operation that can be used in the preprocessor that I am aware of.
Does anyone know a simple way of generating this sort of thing at compile time?
You can define them as mathematical expressions:
#define blockbits 8
#define blocksize (1 << blockbits)
#define blockXXXX (blocksize - 1) // changed from blocksize to blockXXXX, since blocksize is already taken
The parentheses are to make sure there are no operator precedence issues when you use them in other expressions.
You also might want to change the names to all uppercase like BLOCKBITS
, BLOCKSIZE
, etc, which is a C++ naming convention to distinguish macros from normal names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With