添加函数 MathUtil::popcount,用于计算一个数字中二进制1的个数

This commit is contained in:
2025-08-07 22:35:10 +08:00
parent 09eaa78ba1
commit dd72a8e3fd
3 changed files with 52 additions and 0 deletions
+5
View File
@@ -10,6 +10,11 @@ class MathUtil
public:
static size_t ComponentSize(ComponentType ct);
static size_t DataTypeSize(DataType dt);
//count the number of bits set in v
static DV_CORE_API uint32_t popcount(uint8_t v);
static DV_CORE_API uint32_t popcount(uint16_t v);
static DV_CORE_API uint32_t popcount(uint32_t v);
static bool floatEqual(float a, float b,
float tolerance = std::numeric_limits<float>::epsilon()) {
+25
View File
@@ -11,6 +11,31 @@ const float MathUtil::PI_DIV4 = float(0.25 * PI);
const float MathUtil::fDeg2Rad = PI / float(180.0);
const float MathUtil::fRad2Deg = float(180.0) / PI;
static const uint8_t kBitsSetTable256[256] =
{
#define B2(n) n, n+1, n+1, n+2
#define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)
#define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)
B6(0), B6(1), B6(1), B6(2)
};
uint32_t MathUtil::popcount(uint8_t v)
{
return kBitsSetTable256[v];
}
uint32_t MathUtil::popcount(uint16_t v)
{
return kBitsSetTable256[v & 0xff] + kBitsSetTable256[(v >> 8) & 0xff];
}
uint32_t MathUtil::popcount(uint32_t v)
{
return kBitsSetTable256[v & 0xff] + kBitsSetTable256[(v >> 8) & 0xff] +
kBitsSetTable256[(v >> 16) & 0xff] + kBitsSetTable256[v >> 24];
}
size_t MathUtil::ComponentSize(ComponentType ct)
{
switch (ct)