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));
}
【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】
© 版权声明
本平台(www.cooy.cn)的一切软件、教程及内容信息仅限用于学习和研究,付费仅为收集整理归类费用;
不得将上述内容用于商业或者非法用途,否则一切后果用户自行承担负责。本平台资源、内容、信息均来自来自用户上传,版权争议及其他问题与本平台无关。
您必须在下载后的24个小时之内从您的电脑或手机中彻底删除上述下载内容,如果您喜欢该程序或内容,请支持正版以获取更好的服务。我们非常重视版权问题,如有侵权请发送邮件至下方邮件(655465@qq.com),敬请谅解!
如发现违法违规内容,请联系下方邮箱举报,我们收到后将会第一时间处理。
THE END
暂无评论内容