I'd like to have a function or (preferably) a macro that calculates the number of shifts required to obtain a certain bit mask.
Currently I do something like:
#define CURRBITMASK 0x30
#define CURRBITSHIFT 4
What I want to do:
#define BITMASK1 0x10
#define BITSHIFT1 GETSHIFT(BITMASK1) // 4 ; 0x10 = (0x1 << 4)
#define BITMASK2 0x18
#define BITSHIFT2 GETSHIFT(BITMASK2) // 3 ; 0x18 = (0x3 << 3)
#define BITMASK3 0xC0
#define BITSHIFT3 GETSHIFT(BITMASK3) // 6 ; 0xC0 = (0x3 << 6)
#define BITMASK4 0x40
#define BITSHIFT4 GETSHIFT(BITMASK3) // 6 ; 0x40 = (0x1 << 6)
Is there any way to obtain the required shift from the mask using a macro only? If not, is there a more optimal way to do it as a function than this?:
int get_shift(int bitmask) {
int count = 0;
while (bitmask & 0x1) {
bitmask >>= 1;
count++;
}
return count;
}