u010089114 2015-09-17 08:53 采纳率: 75%
浏览 1456
已采纳

关于按位与在这个程序的的实际意义,看我注释

public class VoteMsgBinCoder implements VoteMsgCoder{
public static final int MIN_WIRE_LENGTH = 4;
public static final int MAX_WIRE_LENGTH = 16;
public static final int MAGIC = 0x5400;
public static final int MAGIC_MASK = 0xfc00;
public static final int MAGIC_SHIFT = 8;
public static final int RESPONSE_FLAG = 0x0200;
public static final int INQUIRE_FLAG = 0x0100;
public VoteMsg fromWire(byte[] input) throws IOException {
ByteArrayInputStream bs = new ByteArrayInputStream(input);
DataInputStream in = new DataInputStream(bs);
int magic = in.readShort();
/*为什么是和MAGIC_MASK进行位与运算呢,为什么是和MAGIC进行比较呢,而不是其他数,小弟对位运算不是很明白*/
if ((magic & MAGIC_MASK) != MAGIC) {
throw new IOException("Bad Magic #: " +
((magic & MAGIC_MASK) >> MAGIC_SHIFT));
}

      boolean resp = ((magic & RESPONSE_FLAG) != 0);
      boolean inq = ((magic & INQUIRE_FLAG) != 0);
      int candidateID = in.readShort();
      if (candidateID < 0 || candidateID > 1000) {
      throw new IOException("Bad candidate ID: " + candidateID);
      }
      long count = 0;
      if (resp) {
      count = in.readLong();
      if (count < 0) {
      throw new IOException("Bad vote count: " + count);
      }
      }
      // Ignore any extra bytes
      return new VoteMsg(resp, inq, candidateID, count);
      }  

}

  • 写回答

2条回答 默认 最新

  • threenewbee 2015-09-17 10:36
    关注

    (magic & MAGIC_MASK) != MAGIC)

    magic是一组二进制位开关
    MAGIC_MASK作为参照
    这里的意思就是,判断MAGIC_MASK标记为1的字段,在magic中是否全为1

    举例
    m M m&M m&M==M
    00 01 00 0
    01 01 01 1
    10 01 00 0
    11 01 01 1

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已采纳回答 9月11日

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数