That's cool and thankyou but it's also really bloody slow.
I found this great page (where I got the masking hack from):
http://graphics.stanford.edu/~seander/bithacks.html
Your reply tipped me off that I was trying to find log base 2, so I figured out what it was I was looking for on the bit hacks page. The following example is nearly ten times faster (tested) that the float method.
It was the only trick there that I could easily translate into Java. If anyone knows how to translate the quicker ones I'd be really grateful. (
This one looked faster with only 7 operations, but I will stick to this one for now if no one feels like tackling it).
Code:
static final int [] MultiplyDeBruijnBitPosition = {
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
int timer;
void setup(){
int b = unbinary("0000100100000");
int q = 0;
timer = millis();
for(int i = 0; i < 1000000; i++){
q = bitLog1(b);
}
println(millis() - timer);
q = 0;
timer = millis();
for(int i = 0; i < 1000000; i++){
q = bitLog2(b);
}
println(millis() - timer);
}
int bitLog1(int num){
num |= num >> 1; // first round down to power of 2
num |= num >> 2;
num |= num >> 4;
num |= num >> 8;
num |= num >> 16;
num = (num >> 1) + 1;
return MultiplyDeBruijnBitPosition[(num * 0x077CB531) >> 27];
}
int bitLog2(int num){
return round(log(num)/log(2));
}