位运算概览

实际操作
方法定义:
public class BitUtils{
public BitUtils() { }
public static boolean isTrue(Long status, Long code) { return (status & code) != 0L; } // status包含code
public static boolean isEnable(Long status, Long code) { return (status & code) == code;} // status等于code
public static boolean isFalse(Long status, Long code) { return !isTrue(status, code); } // status不包含code
public static Long enable(Long status, Long code) { return status | code; } // status和code累加
public static Long disable(Long status, Long code) { return status & ~code;} // status减去code
}
状态定义:
public class AssetTagConstants {
public static final long PRIVACY = 1L << 0;
public static final long LOW_CIRCULATION = 1L << 1;
public static final long DELISTED = 1L << 2;
}
一个字段(tagBits)表示多个状态(PRIVACY,LOW_CIRCULATION,DELISTED)
方法调用:
public boolean isDelisted(){
return Optional.ofNullable(tagBits)
.map(tagBits ->BitUtils.isTrue(tagBits, AssetTagConstants.DELISTED)) //tagBits包含delisted的值
.orElse(false);
}
public void setDelisted(Boolean delisted) {
if(delisted == null ){
return;
}
long tagBits = Optional.ofNullable(this.tagBits).orElse(0L);
if(delisted){
tagBits = BitUtils.enable(tagBits, AssetTagConstants.DELISTED); // tagBits加上delisted的值
}
else{
tagBits = BitUtils.disable(tagBits, AssetTagConstants.DELISTED); // tagBits去掉delisted的值
}
this.tagBits = tagBits;
}