关于二进制的一些用法

二进制的基本使用

        int a = 4, b = 6;
        System.out.println("4的二进制是 " + Integer.toBinaryString(a));//100
        System.out.println("6的二进制是 " + Integer.toBinaryString(b));//110

//        & 规则:1&1=1, 1&0=0, 0&0=0
        System.out.println("4&6 " + Integer.toBinaryString(4 & 6));//100

//        | 规则:1|1=1, 1|0=1, 0|0=0
        System.out.println("4|6 " + Integer.toBinaryString(4 | 6));//110

//        ~ 规则:~1=0, ~0=1
        System.out.println("~4 " + Integer.toBinaryString(~4));//11111111111111111111111111111011

//        ^ 规则:1^1=0, 0^0=0, 1^0=1
        System.out.println("4^6 " + Integer.toBinaryString(4 ^ 6)); //10

//        任何整数a与b(b=2的n次方)取余=a&(b-1)
        System.out.println("345%16 " + (345 % 16) + " or " + (345 & (16 - 1))); //9 or 9

二进制的实用场景

  1. jdk权限管理
  2. 判断商品是否有某种属性

他们的原理都是一样的。一个位上要么是1,要么是0,1表示拥有,0表示不拥有。这样对于原本需要用多个变量来表示的属性拥有关系可以直接用一个int值来表示。(java中int是32位,如果要表示的属性多于31可以使用long。)

二进制权限demo


public class Permission {

    private static final int ALLOW_INSERT = 1 << 0; //1
    private static final int ALLOW_DELETE = 1 << 1; //2
    private static final int ALLOW_UPDATE = 1 << 2; //4
    private static final int ALLOW_SELECT = 1 << 3; //8
    //    表示拥有的权限
    private int flag = 0;

    public int getFlag() {
        return flag;
    }

    //    添加权限
    public void enable(int permission) {
        flag = flag | permission;
    }

    public void enable(int... permission) {
        for (int p : permission) {
            flag = flag | p;
        }
    }

    //    禁用权限
    public void disenable(int permission) {
        flag = flag & (~permission);
    }

    //    查看是否有某一权限
    public boolean has(int permission) {
        return permission == (permission & flag);
    }

    //    查看是否没有某一权限
    public boolean noHas(int permission) {
        return 0 == (permission & flag);
    }

    public static void main(String[] args) {
        Permission p = new Permission();
        p.enable(ALLOW_INSERT);
        System.out.println("有了 添加 " + p.getFlag());
        p.enable(ALLOW_DELETE, ALLOW_UPDATE, ALLOW_SELECT);
        System.out.println("有了 删改查 " + p.getFlag());
        p.disenable(ALLOW_INSERT);
        System.out.println("没了 添加 " + p.getFlag());
        System.out.println("是否有 删除 " + p.has(ALLOW_DELETE));
        System.out.println("是否有 添加 " + p.has(ALLOW_INSERT));
        System.out.println("是否没有 查看 " + p.noHas(ALLOW_SELECT));

    }

}

猜你喜欢

转载自blog.csdn.net/weixin_37077950/article/details/83539092
今日推荐