Search code examples
pythonbitboard

How to print out bitboards correctly in Python


I want to program a chess engine using bitboards. Because I am not very familiar with bitboards I am trying to figure out first how to use them. I wrote a small function which should print the bitboard. That's where I stumbled upon a problem. My function seems to print out the ranks correctly but doesn't seem to print out the files correctly.

def print_bitboard(bitboard):
    board = str(bin(bitboard)).zfill(64)
    for i in range(8):
    print(board[8*i+0] + " " + board[8*i+1] + " " + board[8*i+2] + " " + 
          board[8*i+3] + " " + board[8*i+4] + " " + board[8*i+5] + " " + 
          board[8*i+6] + " " + board[8*i+7])


bitboard1 = 
int("0000000000000000000000000000000000000000000000001111111100000000", 2)  
# 2nd rank
bitboard2 = 
int("1000000010000000100000001000000010000000100000001000000010000000", 2)  
# file A

print_bitboard(bitboard1)
print("")
print_bitboard(bitboard2)

Result:

0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 b
1 1 1 1 1 1 1 1 
0 0 0 0 0 0 0 0

0 b 1 0 0 0 0 0     ----> wrong, should be: 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0

Solution

  • The bin function always returns a valid Python representation of a binary literal starting with 0b. If you not want it you can use the str.format method instead:

    board = '{:064b}'.format(bitboard)