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);
            }
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM