In writing some logic code for an octree, I've come across a situation where I
have to find the most-significant non-zero bit of an integer.
I can see how this might be done via a brute-force scan through the bits:
integer :: mynumber,i
do i = BIT_SIZE(i),1,-1
if(BTEST(mynumber,i-1)) exit
enddo
But can anyone suggest a more-efficient way of doing this? Essentially, I'm
looking for an integer log_2() function.
cheers,
Rich
> In writing some logic code for an octree, I've come across a situation
> where I have to find the most-significant non-zero bit of an integer.
Hardware normally has an instruction to do just this. F08 has the
LEADZ intrinsic to encourage the compiler to map directly to the
appropriate machine instruction. See also TRAILZ. Since the cost
of implementation is about zilch you might find that compilers you
are interested in may already have these intrinsics. ifort for
example has had them for years.
--
write(*,*) transfer((/17.392111325966148d0,6.5794487871554595D-85, &
6.0134700243160014d-154/),(/'x'/)); end
The second is the (previously suggested) binary search. Check if
greater than 2**16 then either 2**24 or 2*8, etc. One can use a 32 (or
31 depending on various things) long table for better speed. Or one
could shift a 1 into place for the comparison.
Both are easy to code and resaonably fast.
Thanks for the suggestion. For the gfortran gurus in the forum, how can I submit
a feature request to get these routines implemented?
cheers,
Rich
The mailing list and/or Bugzilla (and if you omit one of those, it
should probably be the mailing list).
The 256 word integer table would contain the byte power contributions
15,14,14........1,0
They are now implemented (I hope I made no mistakes ;-). Snapshots and
precompiled binaries newer than today should include LEADZ and TRAILZ.
Gr.
Steven