diff --git a/hutool-core/src/main/java/org/dromara/hutool/core/util/ByteUtil.java b/hutool-core/src/main/java/org/dromara/hutool/core/util/ByteUtil.java index 4a2d8f14d..a7d29c29b 100644 --- a/hutool-core/src/main/java/org/dromara/hutool/core/util/ByteUtil.java +++ b/hutool-core/src/main/java/org/dromara/hutool/core/util/ByteUtil.java @@ -14,11 +14,14 @@ package org.dromara.hutool.core.util; import org.dromara.hutool.core.io.buffer.FastByteBuffer; import org.dromara.hutool.core.math.NumberUtil; +import org.dromara.hutool.core.text.StrUtil; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteOrder; import java.nio.charset.Charset; +import java.util.LinkedList; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.DoubleAdder; @@ -629,4 +632,39 @@ public class ByteUtil { } return buffer.toArrayZeroCopyIfPossible(); } + + /** + * 统计byte中位数为1的个数 + * + * @param buf 无符号bytes + * @return 为 1 的个数 + */ + public static int bitCount(final byte[] buf) { + int sum = 0; + for (byte b : buf) { + sum += Integer.bitCount((b & 0xFF)); + } + return sum; + } + + /** + * 统计无符号bytes转为bit位数为1的索引集合 + * + * @param bytes 无符号bytes + * @return 位数为1的索引集合 + */ + public static List toUnsignedBitIndex(final byte[] bytes) { + List idxList = new LinkedList<>(); + StringBuilder sb = new StringBuilder(); + for (byte b : bytes) { + sb.append(StrUtil.padPre(Integer.toBinaryString((b & 0xFF)), 8, "0")); + } + final String bitStr = sb.toString(); + for (int i = 0; i < bitStr.length(); i++) { + if (bitStr.charAt(i) == '1') { + idxList.add(i); + } + } + return idxList; + } } diff --git a/hutool-core/src/test/java/org/dromara/hutool/core/util/ByteUtilTest.java b/hutool-core/src/test/java/org/dromara/hutool/core/util/ByteUtilTest.java index ff645eebf..5b49fbe3b 100644 --- a/hutool-core/src/test/java/org/dromara/hutool/core/util/ByteUtilTest.java +++ b/hutool-core/src/test/java/org/dromara/hutool/core/util/ByteUtilTest.java @@ -12,11 +12,13 @@ package org.dromara.hutool.core.util; +import org.dromara.hutool.core.lang.Console; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.util.List; public class ByteUtilTest { @Test @@ -191,4 +193,19 @@ public class ByteUtilTest { aShort = wrap.getShort(); Assertions.assertEquals(a, aShort); } + + @Test + public void toUnsignedBitIndex() { + byte[] bytes = {0, 13, -64, -31, 101, 88, 47, -64}; + List list = ByteUtil.toUnsignedBitIndex(bytes); + Console.log(list); + } + + @Test + public void bitCount() { + byte[] bytes = {0, 13, -64, -31, 101, 88, 47, -64}; + int count = ByteUtil.bitCount(bytes); + Console.log(count); + Assertions.assertEquals(count, ByteUtil.toUnsignedBitIndex(bytes).size()); + } }