java中通过位运算实现多个状态的判断

通过 <<  |  & ~ 位运算,实现同时拥有多个状态

 

通过 << 定义数据的状态

复制代码
public interface LogConstants {
    /**
     * 消耗标记
     */
    short COST_ASSET = 1 << 0;
    short COST_GOLD = 1 << 1;
    short COST_BINDGOLD = 1 << 2;
    short COST_SOPH = 1 << 3;
    short COST_STRSOUL = 1 << 4;
    short COST_REFSOUL = 1 << 5;
    short COST_SOULSTONE = 1 << 6;
    short COST_AAMHID = 1 << 7;
    short COST_REALM = 1 << 8;
}
复制代码

 

通过 |= 加入多个状态

复制代码
short mark = 0;
        int costSoph = channel.getSoph();
        if (costSoph > 0) {
            mark |= LogConstants.COST_SOPH;
        }

        if (costGold > 0) {
            mark |= LogConstants.COST_GOLD;
        }
复制代码

 

通过 (m & LogConstants.COST_ASSET) > 0 判断是否拥有该状态

通过 m = (short) (m & ~LogConstants.COST_ASSET);扣除该状态

复制代码
public void addCostLog(LogEvent event, Player player, short mark, int... args) {short m = mark;
        for (int i : args) {
            if ((m & LogConstants.COST_ASSET) > 0) {
                m = (short) (m & ~LogConstants.COST_ASSET);
                cost.setAsset(i);
            } else if ((m & LogConstants.COST_GOLD) > 0) {
                m = (short) (m & ~LogConstants.COST_GOLD);
                cost.setGold(i);
            } else if ((m & LogConstants.COST_BINDGOLD) > 0) {
                m = (short) (m & ~LogConstants.COST_BINDGOLD);
                cost.setBindGold(i);
            } else if ((m & LogConstants.COST_SOPH) > 0) {
                m = (short) (m & ~LogConstants.COST_SOPH);
                cost.setSoph(i);
            } else if ((m & LogConstants.COST_STRSOUL) > 0) {
                m = (short) (m & ~LogConstants.COST_STRSOUL);
                cost.setStrSoul(i);
            } else if ((m & LogConstants.COST_REFSOUL) > 0) {
                m = (short) (m & ~LogConstants.COST_REFSOUL);
                cost.setRefSoul(i);
            } else if ((m & LogConstants.COST_SOULSTONE) > 0) {
                m = (short) (m & ~LogConstants.COST_SOULSTONE);
                cost.setSoulStone(i);
            } else if ((m & LogConstants.COST_AAMHID) > 0) {
                m = (short) (m & ~LogConstants.COST_AAMHID);
                cost.setAamhid(i);
            } else if ((m & LogConstants.COST_REALM) > 0) {
                m = (short) (m & ~LogConstants.COST_REALM);
                cost.setRealm(i);
            }
        }
    }
复制代码

 

http://www.cnblogs.com/zhuawang/p/3948344.html
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值