mirror of
https://github.com/PX4/PX4-Autopilot.git
synced 2026-11-25 00:30:50 +08:00
fix(math): add countTrailingZeros with unit tests also use compiler builtin function for countSetBits
This commit is contained in:
1 parent
545f6568a2
commit
a808eeec97
2 files changed
+18
-7
No files matched your search
@@ -275,14 +275,13 @@ constexpr int16_t negate<int16_t>(int16_t value)
|
||||
template<typename T>
|
||||
int countSetBits(T n)
|
||||
{
|
||||
int count = 0;
|
||||
return __builtin_popcount(n);
|
||||
}
|
||||
|
||||
while (n) {
|
||||
count += n & 1;
|
||||
n >>= 1;
|
||||
}
|
||||
|
||||
return count;
|
||||
template<typename T>
|
||||
int countTrailingZeros(T n)
|
||||
{
|
||||
return n == 0 ? (int)(sizeof(T) * 8) : __builtin_ctz(n);
|
||||
}
|
||||
|
||||
inline bool isFinite(const float &value)
|
||||
|
||||
@@ -225,6 +225,18 @@ TEST(FunctionsTest, countSetBits)
|
||||
EXPECT_EQ(countSetBits(754323), 9);
|
||||
}
|
||||
|
||||
TEST(FunctionsTest, countTrailingZeros)
|
||||
{
|
||||
EXPECT_EQ(countTrailingZeros(1u), 0);
|
||||
EXPECT_EQ(countTrailingZeros(2u), 1);
|
||||
EXPECT_EQ(countTrailingZeros(8u), 3);
|
||||
EXPECT_EQ(countTrailingZeros(256u), 8);
|
||||
EXPECT_EQ(countTrailingZeros(0xffffffffu), 0);
|
||||
EXPECT_EQ(countTrailingZeros(0x80000000u), 31);
|
||||
EXPECT_EQ(countTrailingZeros(0u), 32);
|
||||
EXPECT_EQ(countTrailingZeros((uint8_t)0u), 8);
|
||||
}
|
||||
|
||||
TEST(FunctionsTest, isFiniteVector3f)
|
||||
{
|
||||
EXPECT_TRUE(isFinite(matrix::Vector3f()));
|
||||
|
||||
Reference in new issue
Block a user