1. 二进制掩码
- 通过按位逻辑运算(如 AND、OR 或 NOT),可以实现对目标数据特定位置比特的选择、设置或清除
1.1 进制转换
@Test
public void toBinary() {
long value = (long) Math.pow(2, 2);
System.out.println(Long.toBinaryString(value));
}
@Test
public void toData() {
String binary = "110";
int data = Integer.parseInt(binary, 2);
int data2 = Integer.valueOf(binary, 2);
System.out.println(data + "; " + data2);
}
2. 选择特定位 (按位与 &)
- 用掩码选择字节中的特定位
数据 101
掩码 100
结果 100
示例:
public enum AbnormalFlagEnum {
ABNORMAL_ZERO((long) Math.pow(2, 0), "二进制:1"),
ABNORMAL_ONE((long) Math.pow(2, 1), "二进制:10"),
ABNORMAL_TWO((long) Math.pow(2, 2), "二进制:100"),
;
private Long code;
private String desc;
AbnormalFlagEnum(Long code, String desc) {
this.code = code;
this.desc = desc;
}
public Long getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static AbnormalFlagEnum getByCode(String code) {
if (code == null) {
return null;
}
for (AbnormalFlagEnum value : values()) {
if (value.getCode().equals(code)) {
return value;
}
}
return null;
}
}
@Test
public void mask() {
long abnormalFlag = 5;
long mask = AbnormalFlagEnum.ABNORMAL_TWO.getCode();
System.out.println(Long.toBinaryString(abnormalFlag) + " & " + Long.toBinaryString(mask) + " = "
+ Long.toBinaryString(abnormalFlag & mask));
System.out.println((abnormalFlag & mask) == mask);
System.out.println((abnormalFlag & mask) > 0);
}
打印结果:
101 & 100 = 100
true
true
3. 设置特定位 (按位或 |)
数据 101
掩码 100
结果 101
示例:
@Test
public void calBit() {
long source = (long) Math.pow(2, 2);
source |= 5;
source |= 6;
System.out.println(Long.toBinaryString(source));
}
4. 清除特定位 (按位异或 ^)
数据 1100
掩码 100
结果 1000
示例:
@Test
public void clearBit() {
long mask = (long) Math.pow(2, 2);
int binary = Integer.parseInt("1100", 2);
binary ^= mask;
System.out.println(Long.toBinaryString(binary));
}
网友评论