aboutsummaryrefslogtreecommitdiff
path: root/src/bitboard.c
blob: c0abbf84d339cbb121993d51049b0e43eb6ac16d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include "bitboard.h"

/* Print bitboard on screen in the same way squares appear in memory
 * (i.e the board is actually flipped along X) */
void printBitboard(Bitboard bb) {
  for (U64 index = 0; index < 64; index++) {
    printf("%lu", (bb >> index) & 1);
    if ((index + 1) % 8 == 0) printf("\n");
  }
  printf("\n\n");
}

/* Return bitboard cardinality, aka number of elements in the set */
inline int popCount(Bitboard bb){
  if (bb == 0) return 0;
  return popCount(bb >> 1) + (bb & 1);
}

/* Return Bitboard with only Least Single Bit */
inline Bitboard ls1b(Bitboard bb) {
  return bb & -bb;
}

/* Log base 2 (aka Trailing Zero Count)
 * Only works for SINGLE Bitboards
 * Useful for calculating bit-index of LS1B */
inline int bitscan(Bitboard bb) {
  return popCount(ls1b(bb) - 1);
}

/* Bitscan forward with LS1B reset */
inline int bitscanAndReset(Bitboard* bb) {
  int idx = bitscan(*bb);
  *bb &= *bb - 1;
  return idx;
}