Skip to content

Commit

Permalink
Added round_pow2 function for rounding integer values up to power of 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sadko4u committed Sep 20, 2023
1 parent b476fc5 commit 4ea20be
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

=== 1.0.32 ===
* Added realloc_aligned function.
* Added round_pow2 function for rounding integer values up to power of 2.

=== 1.0.31 ===
* Fixed several issues reported by PVS Studio static analyzer.
Expand Down
15 changes: 15 additions & 0 deletions include/lsp-plug.in/common/bits.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,20 @@ namespace lsp
#endif
#undef LSP_PLUG_IN_COMMON_BITS_IMPL

namespace lsp
{
/**
* Round the integer value up to power of 2
* @tparam T integer value
* @param value value to round
* @return rounded value
*/
template <class T>
T round_pow2(T value)
{
T rounded = 1 << int_log2(value);
return (rounded == value) ? rounded : rounded << 1;
}
} /* namespace lsp */

#endif /* LSP_PLUG_IN_COMMON_BITS_H_ */
13 changes: 13 additions & 0 deletions src/test/utest/bits.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ UTEST_BEGIN("common", bits)
}
}

void test_pow2_rounding()
{
uint32_t x = 0x100;

printf("Testing round_pow2...\n");

UTEST_ASSERT(round_pow2(x) == x);
for (uint32_t i = 1; i<=x; ++i)
UTEST_ASSERT(round_pow2(x + i) == (x << 1));
}

UTEST_MAIN
{
test_reverse_bits<uint8_t>("reverse_bits u8");
Expand All @@ -91,6 +102,8 @@ UTEST_BEGIN("common", bits)
test_int_log2<int32_t>("int_log2 i32");
test_int_log2<uint64_t>("int_log2 u64");
test_int_log2<int64_t>("int_log2 i64");

test_pow2_rounding();
}

UTEST_END;
Expand Down

0 comments on commit 4ea20be

Please sign in to comment.