I need to find the highest order 1 in some longs, ints, and shorts in Java. For example, if I had a char that looked like 00110101
, I need a method that will return 2 (index of highest order 1).
Now, I know that you can do this using a for loop like:
for(int i=0; i<8; i++)
if((x & 1<<i) != 0) return i;
return -1;
but this is way slower than what I want to do. I know modern CPUs have instructions that do this on chip, so I want to know how I can make a call to that rather than having an explicit loop.
EDIT: Bonus points if you can just return the indices of all of the ones in the primitive.
Thanks.