I'm trying to find a cheap way of calculating log2. To be more precise, I want to identify the bit position of 0B10000000, 0B01000000,... 0B00000001.
When I say 'cheap', I'd rather not use log(x)/log(2) and need it to be #define'd in a macro, so the usual shift loops don't necessarily work. I've tried Google but can't seem to phrase the query that produces results.
The purpose is to #define a BUFFER_LENGTH of 8, 16, 32, 64, 128 or 256 bytes, using 3, 4, 5, 6, 7 or 8 later in a shift operation that will divide the sum of the contents of the buffer by the number of elements in the buffer. All of this needs to be performed by the pre-processor. Right now I have this
Why don't you go the opposite way and just define BUFFER_INDEX, then it's easy to create BUFFER_LENGTH through a bit shifting that the processor will do for you?
I prefer @J-M-L's original suggestion because the '__builtin_ctz' technique won't give the desired result if you specify a BUFFER_LENGTH value that's not a power of 2.
@gfvalvo I appreciate that and it does have merit. It force the buffer to be of a prescribed length which needs to be a power of 2. The index created by the value is later used also as the FIFO buffer pointer so there is automatic rollover. So, like everything else, fast, good, cheap - pick two.