Convert ring counter to binary

GCC/G++ has a builtin function to count the number of leading zeros of an int (__builtin_clz), and long/long long versions (__builtin_clzl and __builtin_clzll). In looking at the compiler code, it looks like __builtin_clz and friends calls into the library, and there they have assembly versions of the routines.

So you would want something like:

n = 16 - __builtin_clz (x);

Now, if you ever plan to move your code to a different machine, such as an ARM, you probably should use this instead:

n = (sizeof (int) * 8) - __builtin_clz (x);

As I said, AVR doesn't seem to have an instruction built in that does count leading zero in one operation, but other machines do, such as x86, powerpc, and arm5. Given the library routine is written in assembler, it is probably faster than the shift and loop function.