Checkerboard implementation in Java

I am looking to create a basic chess (or unsuccessful, checkers / drafts) engine. After exploring the topic, I'm pretty sure I want to use a series of bits. I understand the concept at a basic level, but I'm having trouble representing them in Java.

I tried to represent the white chessboard pieces as 1 and everything else as 0 with long:

long whitePieces = 0000000000000000000000000000000000000000000000001111111111111111L; 

But when I print it, I get the following 46 bits:

 System.out.println(Long.toBinaryString(whitePieces)); 1001001001001001001001001001001001001001001001 

What causes this result? I am sure that there is something here that I fundamentally misunderstand here; If anyone could point me in the right direction, I would be very grateful.

+5
source share
2 answers

Add 0b in front of your long one to say that it is a binary number.

 long whitePieces = 0b0000000000000000000000000000000000000000000000001111111111111111L; ^^ 
Prefix

( 0b was introduced in Java 7. If you are using an older version, you can do Long.parseLong("000...111", 2) )


Another approach: how about creating an enumeration:

 enum ChessPiece { Pawn, Knight, ... }; 

and save the board in ChessPiece[8][8] . This should provide you with a cleaner interface for reading and changing state than the long message gives you.

If you are concerned about performance, just keep the actual view properly encapsulated in the Board class (make the actual data structure private). If you later find that ChessPiece[8][8] is a bottleneck, you can play around and effortlessly change it to long .

+9
source

You do not store a binary number, but a decimal. To create a number using binary notation, you need to attach it to 0b . See Oracle docs in binary literals .

In addition, one tile or part of a chessboard cannot be represented by one bit at all, so you may want to rethink your decision as a whole.

-1
source

Source: https://habr.com/ru/post/1200387/


All Articles