Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: getting the least significant bit.. optimizing java :]

Author: Andreas Rueckert

Date: 11:50:08 08/13/03

Go up one level in this thread


Hi!

I'm from the Java-Chess project ( http://www.java-chess.de ) and here's our
method to find the msb (not lsb!):

/**
 * This class provides utility methods to manipulate bitmasks.
 */
public class BitUtils {

    /**
     * The highest set bit for all byte values.
     */
    private static int [] _highestBit = {
-1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,

5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,

6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,

6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,

7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,

7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,

7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,

7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 };

    /**
     * Find the index of highest set bit in a long bitmask.
     *
     * @param bitmask The bitmask to operate on.
     *
     * @return The index of the highest set bit or 0, if no bits are set.
     */
    public static final int getHighestBit( long bitmask) {
        int highestBit = 0;

        // The following 3 statements split the 64 bit word down to
        // a byte.

        int dwordPart = (int)(bitmask >>> 32);

        if( dwordPart != 0) {
            highestBit += 32;
        } else {
            dwordPart = (int)bitmask;
        }

        int wordPart = (dwordPart >>> 16) & 0xFFFF;

        if( wordPart != 0) {
            highestBit += 16;
        } else {
            wordPart = dwordPart & 0xFFFF;
        }

        int bytePart = (wordPart >>> 8) & 0xFF;

        if( bytePart != 0) {
            highestBit += 8;
        } else {
            bytePart = wordPart & 0xFF;
        }

        // Use the byte as a index for a precomputed array
        // of bit indexes.
        return highestBit + _highestBit[ bytePart];
    }
}



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.