【问题标题】:Set value in Bitfield variable在位域变量中设置值
【发布时间】:2016-10-04 19:50:50
【问题描述】:

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

  • 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,似乎工作,但我无法弄清楚前者。谢谢!

【问题讨论】:

  • 参数se是什么意思,这个方法应该返回什么?
  • s 是状态,e 是这个参数的新值(见编辑)。
  • nm...我想我明白了。
  • 请注意,调用setHalfMoves(s, 13) 没有任何效果,因为您的班级State 没有任何状态。

标签: java bit-manipulation chess bitmask


【解决方案1】:

首先,您的#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
}

所以你的第一个问题是新值与旧值的 ORing 是错误的操作。对于“设置”类型的功能,您需要将其归零。您的第二个问题是您必须在通过setHalfMoves(int, int) 操作它之后重新分配s。您还必须修复 #setEPSquare(),但我将其留给您尝试。

【讨论】:

  • 我想我的理解略有不同,我会发帖让你看到。谢谢!
【解决方案2】:

这是我的工作,但不确定它是否 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);
}

【讨论】:

  • 没关系我看错了。基本上和我的回答一模一样
猜你喜欢
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多