F
Francois Grieu
Hi,
in an embedded project, the hardware manufacturer has defined
hardware equates on the tune of
#define BIT2MASK(b) (1<<(b))
#define TIMER_CTRL_FOO BIT2MASK(0) // enable mask for feature FOO
#define TIMER_CTRL_BAR BIT2MASK(5) // enable mask for feature BAR
#define TIMER_CTRL_ZOO BIT2MASK(7) // enable mask for feature ZOO
I need to revert the effect of BIT2MASK, and get back at the bit number
When b is in range [0..7] this can be done with one of
// "straightforward"; first constant is octal for "clarity";
#define MASK2BIT(m) ((01623753433>>(m)%11*3)+5&7)
// short variant suggested by Harald van Dijk
#define MASK2BIT(m)(6773270%((m)+9)%8)
// alternate short variant
#define MASK2BIT(m)(478414%((m)+37)&7)
Can we extend this when b is in range [0..15], or better [0..31],
and still have a conformant and "pure" macro, which evaluate its
argument only once ?
Or/and can we generate a compile-time error when m is
not a power of two ?
Can things be made readable, perhaps at the price of removing the
"purity" requirement (which is admitedly pointless in my case) ?
TIA,
François Grieu
in an embedded project, the hardware manufacturer has defined
hardware equates on the tune of
#define BIT2MASK(b) (1<<(b))
#define TIMER_CTRL_FOO BIT2MASK(0) // enable mask for feature FOO
#define TIMER_CTRL_BAR BIT2MASK(5) // enable mask for feature BAR
#define TIMER_CTRL_ZOO BIT2MASK(7) // enable mask for feature ZOO
I need to revert the effect of BIT2MASK, and get back at the bit number
When b is in range [0..7] this can be done with one of
// "straightforward"; first constant is octal for "clarity";
#define MASK2BIT(m) ((01623753433>>(m)%11*3)+5&7)
// short variant suggested by Harald van Dijk
#define MASK2BIT(m)(6773270%((m)+9)%8)
// alternate short variant
#define MASK2BIT(m)(478414%((m)+37)&7)
Can we extend this when b is in range [0..15], or better [0..31],
and still have a conformant and "pure" macro, which evaluate its
argument only once ?
Or/and can we generate a compile-time error when m is
not a power of two ?
Can things be made readable, perhaps at the price of removing the
"purity" requirement (which is admitedly pointless in my case) ?
TIA,
François Grieu