October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Implement Zobrist Hashing for a Chess Position

Build a chess Zobrist key from piece-square and position-state features, update it incrementally for every move, and verify it against full recomputation.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Implement a chess-position Zobrist hash as the XOR of deterministic random keys for the position’s active features: each piece and square, the side to move, castling rights, and en-passant state. Update the key by XORing out features that disappear and XORing in features that appear; keep a full recomputation routine to verify every incremental update.

What a chess-position hash needs to represent

A Zobrist key is a compact fingerprint of a position’s chosen state. Give each possible feature a bit string, then XOR the keys for all features currently present. XOR is useful because a key cancels itself when applied twice: x ^ k ^ k = x. A move can therefore update a position key by removing old features and adding new ones, instead of hashing the whole board from scratch.

As an Amazon Associate I earn from qualifying purchases.

For a typical chess position, define keys for:

  • Each piece identity on each square. Piece identity includes both color and type.
  • The player to move.
  • The current castling-rights state.
  • The en-passant state, commonly represented by its file.

These features distinguish positions that may have different legal continuations. Stockfish’s position implementation uses piece-square keys, castling keys indexed by rights state, en-passant keys indexed by file, and a side key. The source is on a moving master branch, so implementation details may change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to build the key tables and recompute a position

Choose reproducible keys

A 64-bit unsigned value is a common practical key width, not a universal requirement. Choose a pseudorandom generator and initialize it deterministically if you want the same position to produce the same key across runs, which makes debugging easier. Stockfish initializes its generator with a fixed seed before creating piece-square keys.

#1 Best Overall
Advanced Electronic Chess Board, Smart Computer Chess Set, AI Voice Coach Learning for Kids, ELO 2200+ for Improving Players, Magnetic Large Pieces & Board Perfect for Adults, LCD Display(Black)
  • Master-Level AI Engine: Adjustable difficulty, ELO 2200+, ideal for beginners to advanced players seeking professional-grade challenges.
  • Premium Board & Pieces: Largest-in-class 2.36-inch king and 1.22x1.22-inch squares,14.6-inch in diagonal chess board for clear visibility and comfortable play, avoiding cramped layouts.
  • Magnetic Stability: Strong yet balanced magnets secure pieces, even when the board is inverted, ensuring uninterrupted focus during intense matches.
  • Intelligent Voice Coaching: AI-driven analysis provides real-time feedback on moves, identifying weaknesses and suggesting optimal strategies.
  • Comprehensive Learning Tools: Includes 128 tactical puzzles, 256 classic game scores, and unlimited move takebacks for in-depth study and replay.

Keep the random values private to your program unless you deliberately need compatibility with an established key scheme. A different key table is valid for your own transposition table, but its hashes will not match another implementation’s values.

Define feature-key tables

A straightforward design uses an array indexed by piece identity and square, plus separate keys for side to move, castling-rights combinations, and en-passant files. Index conventions are up to you; the important requirement is that key generation, full recomputation, move making, and unmaking all use the same conventions.

Use full recomputation as the reference

Write a routine that starts with zero and XORs the key for every occupied piece-square pair. Then XOR the side key if the side-to-move convention calls for it, the key for the current castling rights, and the key for the en-passant state when present. Stockfish’s set_state() follows this general setup pattern.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Vonset L6 Electronic Chess Board with LED Lights E-Ink Screen Display
  • 【Chess Computer for Beginners and Kids】Great chess set for beginners and kids with LEDs to prompt you to move; Talking Chess and can get help prompting moves with the "?" button; FUN levels 1-2 to help beginners learn chess in a fun way, and 1000 built-in stalemate puzzles, all to help you learn chess faster.
  • 【Electronic Chess Set for Adults】 Suitable for chess enthusiasts to improve their chess skills. Simulate the real game scenario, time play, and support two violations of the judgments, etc. You can experience the authentic game atmosphere, constantly improve your chess skills and adjust your game status.
  • 【Computer Chess Game】Vonset L6 has rich level settings covering the level distribution from entry to proficiency. This chess computer has a strength of up to 2300 ELO (International tournament standard), which corresponds to the level of the Grandmaster and is suitable for most chess players. Note: The level setting applies to both training mode and match mode.
  • 【Electronic Chess Board】With HD E-ink screen, it can be easily viewed under any light source to protect your eyes; Built-in rechargeable battery, it can be used for up to 8 hours with a full charge; Built-in storage box inside the board, when you don't want to play chess, store the pieces in it, it is convenient to store the chess pieces to avoid losing the chess pieces.
  • 【Magnetic Chess Game】L6 chess sets with a magnetic chess board and pieces. Chess pieces are not easily dislodged when playing chess. You can play chess in a mobile environment. It can be used at home, school, outdoor camping, or traveling.2 extra queens are available for you to use as free accessories.

Do not discard this routine after adding incremental updates. It is a correctness oracle: compare its result with the maintained key after moves, FEN loading, and unmaking.

What to XOR when a piece moves

For an ordinary move, XOR out the moving piece’s source-square key and XOR in its destination-square key. If the move captures a piece, XOR out the captured piece’s key at the capture square. Then update the state features that changed: side to move, castling rights, and en-passant state.

For state features, remove the old key before changing the state value, then add the key for the new value. For example, XOR the old castling-rights key out, update the rights, and XOR the new rights key in. Apply the same pattern to en-passant state. Toggle the side key on every move if your convention represents one side, such as Black, with that key.

Rank #3
Sale
P6 Electronic Chess Board Chess Computer Talking Smart Chess Board Magnetic Electronic Chess Set with LED for Kids & Adults
  • Product Dimensions: 12.6x12.13x0.9 inches (32x30.8x2.3 cm); Game area: 8.8x8.8 inches(22.5x22.5 cm); Each square: 1.1 inches (28x28mm). King height: 2 in. Package list: Electronic chess board, 34 pieces (with extra double queen), two drawstring storage bags, manual, charger cable.
  • Electronic Chess Board: Built-in AI intelligent algorithms, with 1-18 levels for beginners to intermediate players. Play against the computer or a friend, and challenge yourself anytime. The P6 Chess Computer supports up to 1700 ELO.
  • Smart Chess Board: Offers three modes: Training for beginners and kids, Match for improving skills with the device, and Human for two-player games with friends or family. Enjoy leisure time and choose the mode that suits your practice needs.
  • Learn Chess: The P6 features 200 puzzles to enhance your skills. Training mode offers light prompts and voice announcements for each move. Press the '?' button for hints when needed, making learning and playing chess easier.
  • Strong Magnetic Chess Pieces: Features strong magnetic adsorption, keeping pieces secure even when shaken. Move them easily without worry, whether at home or on the go.

Special moves need more than the ordinary move update

  • Promotion: remove the pawn’s source feature and add the promoted piece at the destination; also account for a captured piece if the promotion captures.
  • En-passant capture: remove the captured pawn from its actual square, which is not the destination square, as well as moving the capturing pawn.
  • Castling: update both the king’s and rook’s source and destination piece-square features.
  • Rights loss: a king move, rook move, or relevant rook capture may change castling rights. Hash the resulting rights state rather than inferring rights only from current piece placement.
  • En-passant availability: clear any previous en-passant state and add the new one only according to the convention your engine has chosen.

The order of piece and state XOR operations does not affect the final result, but centralizing these updates makes it less likely that move-making paths will forget a feature.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose position semantics deliberately

Side to move and castling rights

Identical piece placement with different players to move can lead to different legal moves, so include side to move. Castling rights must also be represented independently of where the king and rooks currently stand: once a right is lost, returning a piece to its original square does not restore it.

En-passant convention

Stockfish’s source hashes an en-passant file when its position state has an en-passant square. An engine still needs a consistent policy for positions whose FEN contains an en-passant target that cannot actually be captured legally. Whether such a target distinguishes positions depends on the application’s position-equivalence and repetition rules; the cited implementation extract does not settle every convention. Decide this once and apply it consistently to FEN parsing, hashing, repetition detection, and move generation.

Rank #4
Chessnut Air Electronic Chess Board with AI — Handcrafted Wooden Board, LED Indicators, Adaptive Difficulty, Full Piece Recognition — Play Online on Major Chess Platforms
  • 🪵FULL PIECE RECOGNITION WITH WOODEN-LOOK BOARD - Chessnut Air features a durable plastic-and-wood board with plastic sensor-chip pieces. Beautifully crafted wooden board with embedded LED lights that indicate moves and game status.
  • 🏋️PLAY ONLINE WITH REAL PIECES - Connect through compatible Chessnut apps and integrations to play on supported online chess platforms, including Chess-com and Lichess. Opponent moves are shown on the physical board with built-in LED indicators.
  • ♟️AI TRAINING & GAME ANALYSIS VIA CHESSNUT APP - Practice against AI with adjustable difficulty, review positions, and analyze completed games through the Chessnut App. A practical choice for beginners building habits and experienced players sharpening tactics.
  • 🎯OTB CHESS GAME RECORDING - Use Chessnut Air for face-to-face over-the-board games and store up to 20 games for later review or export.
  • ✈️COMPACT ELECTRONIC CHESS SET - The 13 x 13 x 0.7 in board offers a clean, classic look with hidden LEDs, while the 2.7 in king height keeps the set comfortable for desk, home, club, or travel play.

Halfmove clock and search context

A board-position key does not automatically encode every part of a search state. The halfmove clock can matter to draw-rule handling; whether it belongs in the key or elsewhere in a transposition-table entry depends on the engine’s design. Do not treat a piece-and-rights position hash as a complete representation of all search context.

Validate incremental updates before relying on them

In debug builds, recompute the key from the complete position after every move and assert that it matches the incrementally maintained key. Test positions loaded from FEN and make/unmake round trips, with explicit cases for captures, promotions, en-passant captures, both castling directions, and loss of castling rights.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For unmaking, saving the prior key in the move-state record is often simpler and safer than independently reversing every derived field. Continue to restore the board, rights, en-passant state, and side to move correctly; the saved key is not a substitute for restoring those fields.

Use the hash as a lookup key, not proof of identity

Zobrist hashing is a reproducible indexing scheme, not a cryptographic hash. A finite-width key can collide, so a matching key alone is not a mathematical guarantee that two positions are identical. A transposition table can use the key to find likely matching positions and avoid repeated search work, but its verification strategy should reflect the cost of a false match. Additional verification bits or stored position data are possible design choices; there is no single policy established by the cited material.

For conceptual background on combining random state-feature bit strings with XOR, see MIT OpenCourseWare’s 2018 lecture on hashing. For a transposition-table example, see the Chess Programming Wiki’s transposition-table page.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.