位运算标识状态,适合于mysql一个字段表示多种状态的情况

This commit is contained in:
senssic 2021-05-26 13:56:32 +08:00
parent 389ce1d27e
commit f8244eaa4b

View File

@ -0,0 +1,77 @@
package cn.hutool.core.math;
/**
* 通过位运算表示状态的工具类<br>
* 参数必须是 `偶数` `大于等于0`
*
* @author senssic
* @date 2021-5-26 15:23
*/
public class BitStatusUtils {
/**
* 增加状态
*
* @param states 原状态
* @param stat 要添加的状态
* @return 新的状态值
*/
public static int add(int states, int stat) {
check(states, stat);
return states | stat;
}
/**
* 判断是否含有状态
*
* @param states 原状态
* @param stat 要判断的状态
* @return true
*/
public static boolean has(int states, int stat) {
check(states, stat);
return (states & stat) == stat;
}
/**
* 删除一个状态
*
* @param states 原状态
* @param stat 要删除的状态
* @return 新的状态值
*/
public static int remove(int states, int stat) {
check(states, stat);
if (has(states, stat)) {
return states ^ stat;
}
return states;
}
/**
* 清空状态就是0
* @return
*/
public static int clear() {
return 0;
}
/**
* 检查
* @param args
*/
private static void check(int... args) {
for (int arg : args) {
if (arg < 0) {
throw new IllegalArgumentException(arg + " 必须大于等于0");
}
if ((arg & 1) == 1) {
throw new IllegalArgumentException(arg + " 不是偶数");
}
}
}
}