精妙的位运算

位运算概览

位运算概览

实际操作

方法定义:

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;

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容