Computer Chess Club Archives


Search

Terms

Messages

Subject: Interesting pure C high-bit routine from a post by Robert Harley

Author: Dann Corbit

Date: 17:04:40 05/09/02


From a post by Robert Harley <harley@estephe.inria.fr> on
news:comp.arch.arithmetic ...

static INLINE ulong top_bit(ulong x);

/*-- top_bit ---------------------------------------------------------------*/

/* Returns top bit of x, or 0 if x = 0. */
static INLINE ulong top_bit(ulong x)
{

    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
#if BITS == 64
    x |= x >> 32;
#endif

    return x ^ x >> 1;
} /* end function top_bit */


/*
   (Here ulong = unsigned long etc).
   On Alpha you can do better for 64 bits:
 */

/*-- top_bit ---------------------------------------------------------------*/

/* Returns top bit of x, or 0 if x = 0. */
static INLINE u64 top_bit64(u64 x)
{
    u64             t,
                    y,
                    z;

    z = x >> 1;
    t = x & 0xffffffff00000000UL;
    y = x | z;
    if (t)
        x = t;
    z = y >> 2;
    y |= z;
    t = x & 0xffff0000ffff0000UL;
    z = y >> 4;
    if (t)
        x = t;
    y |= z;
    z = y >> 1;
    t = x & 0xff00ff00ff00ff00UL;
    if (t)
        x = t;

    return x & ~z;
} /* end function top_bit */

I have not bothered to bench it against any of the alternatives yet.



This page took 0 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.