Re: [CHALLENGE] finding rightmost zero bit



Bart Vandewoestyne wrote:

OK folks, time for a new challenge...

My profiler tells me that findpos(n) is a function which my code
seems to be using.  The function looks like:

(snip)

and its purpose is to find the index of the rightmost zero bit in the
base 2 representation of a number n.  The least significant bit has
position 1.

On a twos complement machine IAND(X,-X) will return a value with at most one '1' bit, the rightmost in X. I then suggest:

  function findpos(n) result (pos)

    integer(kind=i4b), intent(in) :: n
    integer(kind=i4b)             :: pos, j
    j=not(n)
    j=iand(j,-j)
    pos=0
    if(j.ne.0) pos=1
    if(iand(j,Z'AAAAAAAA).NE.0) pos=pos+1
    if(iand(j,Z'CCCCCCCC).NE.0) pos=pos+2
    if(iand(j,Z'F0F0F0F0).NE.0) pos=pos+4
    if(iand(j,Z'FF00FF00).NE.0) pos=pos+8
    if(iand(j,Z'FFFF0000).NE.0) pos=pos+16

  end function findpos

I don't believe it was specified what the result should be for a twos complement negative one, but zero seems reasonable to me. It might
be that some of the samples fail in that case.


I assume that i4b is a 32 bit integer, though I don't know that
was stated.

-- glen

.



Relevant Pages

  • Re: Casting an array to integer type
    ... its value when the sign bit is clear must be zero. ... succeed, in any of the three representation schemes, ... the result of the conversion is a trap representation, ... yield a trap representation and produce undefined behavior; ...
    (comp.lang.c)
  • Re: A ones complement sanity check, please
    ... representation of integer constant 0 and now how to zero memory ... errors in the 1's complement -1 and sign magnitude -1 representations. ... My questions are about 1's complement representation of the integer ...
    (comp.lang.c)
  • A ones complement sanity check, please
    ... representation of integer constant 0 and now how to zero memory ... errors in the 1's complement -1 and sign magnitude -1 representations. ... My questions are about 1's complement representation of the integer ...
    (comp.lang.c)
  • Re: Double type precision in java
    ... is a requirement for exact representation of numbers that are all short ... defaulting floating point output to a reasonable precision. ... There are many operations that result in a negative zero. ... The JLS depends on IEEE 754 for specification of multiplication results: ...
    (comp.lang.java.programmer)
  • Re: >FLOAT behavior with null string
    ... of blanks as a representation of zero. ... string of blanks as a valid representation for 0E either, ... floating-point number in the syntax below, its value r and true are ...
    (comp.lang.forth)