在Bitfield变量中设置值

时间:2016-10-04 19:50:50

标签: java bit-manipulation chess bitmask

我使用Bitfield结构来存储国际象棋游戏的棋盘状态,它是一个32位整数。 I' m编码/解码的字段是:

  • epSquare(0从63)

  • 一半移动计数(0到100)

  • 当前玩家(0或1)

  • 4个铸造权利标志

我可以创建和提取“状态”,但我在改变某个特定状态时遇到了麻烦:

/*
    0000 0000 0000 0000 0000 0011 1111 epSquare 0x3f
    0000 0000 0000 0001 1111 1100 0000 halfMoves 0x7f >> 6
    0000 0000 0000 0010 0000 0000 0000 curPlayer 0x1 >> 13;
    0000 0000 0000 0100 0000 0000 0000 Kc 0x4000
    0000 0000 0000 1000 0000 0000 0000 Qc 0x8000
    0000 0000 0001 0000 0000 0000 0000 kc 0x10000
    0000 0000 0010 0000 0000 0000 0000 qc 0x20000
    */

public class State {

   public static int new_state(int epSquare, int halfMoves, int turn, int flags){
        return epSquare | (halfMoves << 6) | (turn << 13) | flags;
  }

   public static int epSquare(int s){
      return s & 0x3f;
   }

   public static int halfMoves(int s){
    return s >> 6 & 0x7f;
  }

  // s state, e new epSquare
  public static int setEPSquare(int s, int e){
     //??
  }

   // s state, h halfMoves value
   public static int setHalfMoves(int s, int e){
   //??
  }

  public static void main (String[] args){
     int s = BoardState.new_state(36, 84, 1, 0);
     System.out.println("ep square: " + epSquare(s)); //36
     System.out.println("half moves: " + halfMoves(s)); //84
     s = setHalfMoves(s, 13);
     System.out.println("half moves: " + halfMoves(s)); //should give 13
  }
 }

如何实施setHalfMoves方法?第一个setEPSquare似乎有效,但我无法弄清楚前者。谢谢!

2 个答案:

答案 0 :(得分:2)

首先,您的#setEPSquare()功能不正确。当我向您展示下面的代码时,您可能会理解为什么,但我也会解释:

public static int setHalfMoves(int s, int e){
     return (
             //mask for e to only the correct bits
             (e & 0x7f)
             //left shifted into position
             << 6)
             //zero out the original value
             | (s & (~(0x7f << 6)));
}
public static void main (String[] args){
   int s = BoardState.new_state(36, 84, 1, 0);
   System.out.println("ep square: " + epSquare(s)); //36
   System.out.println("half moves: " + halfMoves(s)); //84
   //Note that this is fixed to now reassign s
   s = setHalfMoves(s, 13);
   System.out.println("half moves: " + halfMoves(s)); //should give 13
}

所以你的第一个问题是,将新值与旧值进行或运算是错误的操作。您需要将其归零以用于设置&#39;功能类型。您的第二个问题是,在通过s进行操作后,您必须重新分配setHalfMoves(int, int)。你也必须修复#setEPSquare(),但我留给你试试。

答案 1 :(得分:1)

这就是我的工作,但不确定它是否100%正确:

public static int setEpSquare(int s, int ep){
    s&= ~0x3f;
    return s | ep ;     
}

public static int setHalfMoves(int s, int h){
    s&= ~(0x7f << 6);
    return s | (h << 6);
}
相关问题