位图实现一个字段映射多个值

/**
 * 用户角色枚举
 *
 * @author 公众号JAVA前线
 *
 */
public enum UserRoleEnum {

    // 1 -> 00000001
    NORMAL(1, "普通用户"),

    // 2 -> 00000010
    MANAGER(1 << 1, "管理员"),

    // 4 -> 00000100
    SUPER(1 << 2, "超级管理员")

    ;

    // 新增角色 -> 位或操作
    // oldRole -> 00000001 -> 普通用户
    // addRole -> 00000010 -> 新增管理员
    // newRole -> 00000011 -> 普通用户和管理员
    public static Integer addRole(Integer oldRole, Integer addRole) {
        return oldRole | addRole;
    }

    // 删除角色 -> 位异或操作
    // oldRole -> 00000011 -> 普通用户和管理员
    // delRole -> 00000010 -> 删除管理员
    // newRole -> 00000001 -> 普通用户
    public static Integer removeRole(Integer oldRole, Integer delRole) {
        return oldRole ^ delRole;
    }

    // 是否有某种角色 -> 位与操作
    // allRole -> 00000011 -> 普通用户和管理员
    // qryRole -> 00000001 -> 是否有管理员角色
    // resRole -> 00000001 -> 有普通用户角色
    public static boolean hasRole(Integer role, Integer queryRole) {
        return queryRole == (role & queryRole);
    }

    private int code;
    private String description;

    private UserRoleEnum(Integer code, String description) {
        this.code = code;
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public int getCode() {
        return this.code;
    }

    public static void main(String[] args) {
        System.out.println(addRole(1, 2));
        System.out.println(removeRole(3, 1));
        System.out.println(hasRole(3, 1));
    }


public static void main(String[] args) {
    int a=16+8;
    int i = a & 12;
    ArrayList<Integer> list = Lists.newArrayList(2, 4, 8,16);

    for (Integer integer : list) {
      int i1 = integer & a;
      if (i1!=0) {
        System.out.println("----"+integer);
      }
    }

    System.out.println(a|4);
    System.out.println(a|16);
    System.out.println(a&2);
    System.out.println(a&16);
  }
}
posted @ 2022-05-05 15:51  青样儿  阅读(19)  评论(0)    收藏  举报