ALTER EUNCTION [dbo].[f_get_bit_sum]
(
@commiosn_type VARCHAR(100) --字符串 格式 1,2,3
)
RETURNS int
AS
BEGIN
declare @bitSum int set @bitSum = 0结果
SET @commiosn_type += ','--默认在字符串后加逗号
WHILE(charindex(',',@commiosn_type)<>0)--遍历字符串是否有逗号
BEGIN
declare @temp_v int--临时
SET @temp_v = convert(int,substring(@commiosn_type,1,charindex(',',@commiosn_type)-1))--获取截取后的字符串,并且转数字类型
SET @commiosn_type = stuff(@commiosn_type,1,charindex(',',@commiosn_type),',')--把未截取的字符串,重新赋值到变量 @commiosn_type
SET @bitSum =POWER(2, @temp_v-1) + @bitSum--算次方,再相加 (通过按位与运算符计算)
END
return @bitSum
END
java代码
public static Long getBitSum(string numberStr) {
String[] numberArr = numberStr.split(",");
List<String> numberList = Arrays.asList(numberArr);
List<Long> collect = numberList.stream().map(Long::parseLong).collect(Collectors.tolist());
//一行代码
//List<Long> collect = Arrays.stream(numberStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
Long num = 0L;
for(long i : collect) {
double pow = Math.pow(2,i - 1);
num += (long)pow;
}
return num;
}
与上面的方法对应,转换为10进制数组
public static List<Long> getBitList(Long number) {
List<Long> result = new ArrayList<>();
Long i = 1L;
while (number > 0) {
if ((number & 1) == 1) {
result.add(i) ;
}
number = number >> 1;
i++;
}
return result;
}