Determine how many bits in a value

Simplest way is to place the number into a single variable large enough to store the biggest number you'll be dealing with, then left-shift (and count) until the left-most bit (MSB) is not zero, then subtract that count from the size of the variable.

Something like:

int bits(unsigned int val) { // Should work with any size integer.
    unsigned int maxbits = sizeof(val) * 8;
    unsigned int mask = 1 << maxbits-1; // Make sure this is the same size as val
    unsigned int count = 0;
    while (((val & mask) == 0) && (count < maxbits)) {
        val <<= 1;
        count++;
    }
    return maxbits - count;
}

maybe.