一、Java的位运算符实例——与(&)、非(~)、或(|)、异或(^)
1、与(&)
0 & 2 = 0
0 0 00 1 0
0 1 0
2、非(~)
~0 = 7
0 0 01 1 1
3、或(|)
0 & 2 = 2
0 0 00 1 0
0 1 0
4、异或(^)
1 & 2 = 3
0 0 10 1 0
0 1 1
二、运用场景。(类似打标)
public enum FlagEnums {
A(1, "高"),
B(2, "富"),
C(3, "帅"),
;
private int bit;
private String desc;
FlagEnums(int bit, String desc) {
this.bit = bit;
this.desc = desc;
}
/**
* 获取当前Flag十进制的值
*
* @return
*/
public long getBit2Value() {
BigDecimal posValue = new BigDecimal(2);
posValue = posValue.pow(bit);
return posValue.longValue();
}
/**
* 判断Flag中该位有没有打上
*
* @param flag
* @return
*/
public boolean isBitOn(long flag) {
if ((flag & getBit2Value()) == getBit2Value()) {
return true;
}
return false;
}
public int getBit() {
return bit;
}
public void setBit(int bit) {
this.bit = bit;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}