JAvaにおけるビット演算による複数の状態の判断

6093 ワード

通過<< |  & ~ ビット演算、複数の状態を同時に持つことを実現
 
<<でデータの状態を定義する
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);
            }
        }
    }