"It annoys me that I can't find a way to detect and shift all of the trailing zero bits off in one hit - and that I instead have to detect and shift them off one at a time. "
Depending what platform you're on, check if the __builtin_ctz() function is available to you. The ctz stands for 'count trailing zeros'. Use this to get the number of trailing zeros, then shift them all off at once.
Update: I've added in bitCount(), which allows you to send in the number after stripping off the trailing zeros, and returns a count of the remaining bits.
#include <stdio.h>
#include <math.h>
unsigned int bitCount(int num);
void main () {
/* Here's your example number, in binary format for visual purpose
+s */
int num = 0b10100000;
int noTrailingZeros = num >> __builtin_ctz(num);
unsigned int bitsRemain = bitCount(noTrailingZeros);
printf(
"Zeros: %d, No Zeros: %d, Bits remain: %d\n",
num,
noTrailingZeros,
bitsRemain
);
}
unsigned int bitCount(int num) {
unsigned int bits = 0;
while (num) {
bits++;
num >>= 1;
}
return bits;
}
Output:
Zeros: 640, No Zeros: 5, Bits remain: 3