bhlangonijr / chesslib

chess library for legal move generation, FEN/PGN parsing and more
Apache License 2.0
223 stars 78 forks source link

Whitepawn moves Bitboard value index 55 is out of range #106

Closed materoy closed 11 months ago

materoy commented 1 year ago

The line in Bitboard.java

0x8000000000000000L when converted to kotlin results in an overflow error.

Long max value in hex is 0x7FFFFFFFFFFFFFFF

Requesting for comment about this.

bhlangonijr commented 11 months ago

This is language specific. You should use ULong instead of Long in Kotlin to prevent the value going out of range.

val x: ULong = 0x8000000000000000UL

As an example this is a function for flipping bitboards I have in Kotlin:

    // https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating
    @JvmStatic
    fun flipVertical(x: ULong): ULong {
        return ((x shl 56)) or
                ((x shl 40) and 0x00ff000000000000UL) or
                ((x shl 24) and 0x0000ff0000000000UL) or
                ((x shl 8) and 0x000000ff00000000UL) or
                ((x shr 8) and 0x00000000ff000000UL) or
                ((x shr 24) and 0x0000000000ff0000UL) or
                ((x shr 40) and 0x000000000000ff00UL) or
                ((x shr 56))
    }

It won't work correctly if you are working in the Kotlin Long range.

materoy commented 11 months ago

Why ?

bhlangonijr commented 11 months ago

I think you might be confused in thinking that 0x7FFFFFFFFFFFFFFF > 0x8000000000000000L. It is not.

0x8000000000000000L = 0x7FFFFFFFFFFFFFFF + 1 which is greater than Long.MAX_VALUE and that's why you get the error out of range.

Kotlin introduces unsigned long (ULong) which is not present in Java. In java 0x8000000000000000L = -9223372036854775808. In Kotlin ULong 0x8000000000000000UL = 9223372036854775808.