添加函数 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)
+22
View File
@@ -76,4 +76,26 @@ TEST(MathUtil, Basic)
EXPECT_EQ_4X4_T_APPROX(m1, gm1, std::numeric_limits<float>::epsilon() * 100);
}
}
//couting bit set
{
EXPECT_EQ(MathUtil::popcount((uint8_t)(0x0)), 0);
EXPECT_EQ(MathUtil::popcount((uint8_t)(0xFF)), 8);
EXPECT_EQ(MathUtil::popcount((uint16_t)(0x0)), 0);
EXPECT_EQ(MathUtil::popcount((uint16_t)(0xFFFF)), 16);
EXPECT_EQ(MathUtil::popcount((uint32_t)(0x0)), 0);
EXPECT_EQ(MathUtil::popcount((uint32_t)(0xFFFFFFFF)), 32);
for(int32_t i=0; i<100; i++)
{
uint8_t v8 = (uint8_t)MathUtil::rangeRandom(0, 0xFF);
EXPECT_EQ(MathUtil::popcount(v8), __popcnt(v8));
uint16_t v16 = (uint16_t)MathUtil::rangeRandom(0, 0xFFFF);
EXPECT_EQ(MathUtil::popcount(v16), __popcnt(v16));
uint32_t v32 = (uint32_t)MathUtil::rangeRandom(0, 0x7FFFFF);
EXPECT_EQ(MathUtil::popcount(v32), __popcnt(v32));
}
}
}