Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: FirstBit() in assembler

Author: Dan Newman

Date: 10:20:52 01/13/02

Go up one level in this thread


On January 13, 2002 at 08:48:13, David Rasmussen wrote:

>Even though I try to keep my program extremely portable and ANSI/ISO C++
>compliant, except for the parts that can't be, I would like to see how much
>faster my program would be with an inline assembler version of my FirstBit()
>function for use in VC++ (jeez, when will 64-bit processors be common...).
>
>My board setup is a1=0,...,h8=63. For some reason, I can't get it to work.
>
>int FirstBit(BitBoard bitboard)
>{
> __asm {
>        bsr     edx, dword ptr bitboard
>        mov     eax, 0
>        jnz     l1
>        bsr     edx, dword ptr bitboard+4
>        mov     eax, 32
>        jnz     l1
>        mov     edx, -1
>  l1:   add     eax, edx
>        sub     eax, 1
>       }
>}
>
>This is written from me head, as I have deleted what I previously did, so I
>haven't even tried to compile this, but you get the idea. The problem was that
>for some bitboards, it returned the correct value, but for some other bitboards,
>bsr just returned some weird wrong number, which made the entire function return
>some weird wrong number. What's the problem?
>


I don't know what BSF/BSR do to the flags, but if bit zero is set to one,
then BSR will put zero into edx and you won't get the jnz jump.  Also,
when there are no bits set BSR leaves the register undefined (in practice
it leaves it unaffected), so I suspect the flags may not be set one way or
the other.

I do something like this (Dann Corbit's trick):

        bsf eax dword ptr bitboard+4
        add eax 32
        bsf eax dword ptr bitboard

This relies on the eax register being unaffected by the second bsf when
there are no bits set in the lower half of the bitboard--that unaffected
behavior may not be guaranteed forever...  It's the fastest first-bit
I've seen yet--no jumps, no branches, no tests, just three instructions.

>And another question: Last time I checked, Crafty had the same board layout
>(a1=0, h8=63), but it's inline assembler function does something weird which I
>can't understand at all. It checks the upper part of the bitboard first, even
>though this is a _firstbit_ function. I'm puzzled... Maybe it's because I was so
>drunk last night.
>
>/David


I think it's a big-endian/little-endian thing.  Bob likes his most significant
bits to come first, even if the they don't :).

-Dan.



This page took 0.01 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.