Skip to content

Commit feef4dd

Browse files
committed
🐛 Fix fallback implementation of bit_ceil
Problem: - The fallback implementation of `bit_ceil` is implemented incorrectly. In particular it returns the wrong values for exact powers of 2. Solution: - Fix the calculation: subtracting 1 before calculating the bit width is appropriate. Notes: - Thanks to Walter Brown for pointing out this issue in private correspondence. - Undoubtedly, this was missed because of issue #117.
1 parent 0544692 commit feef4dd

2 files changed

Lines changed: 7 additions & 1 deletion

File tree

include/stdx/bit.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ template <typename T>
223223
if (x <= 1U) {
224224
return 1U;
225225
}
226-
return T(1U << bit_width(x));
226+
return T(1U << bit_width(x - 1U));
227227
}
228228

229229
template <typename T>

test/bit.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,13 +160,19 @@ TEMPLATE_TEST_CASE("bit_ceil", "[bit]", std::uint8_t, std::uint16_t,
160160
std::uint32_t, std::uint64_t) {
161161
STATIC_REQUIRE(stdx::bit_ceil(TestType{}) == 1);
162162
STATIC_REQUIRE(stdx::bit_ceil(TestType{1u}) == 1);
163+
STATIC_REQUIRE(stdx::bit_ceil(TestType{3u}) == 4);
164+
STATIC_REQUIRE(stdx::bit_ceil(TestType{4u}) == 4);
165+
STATIC_REQUIRE(stdx::bit_ceil(TestType{5u}) == 8);
163166
STATIC_REQUIRE(stdx::bit_ceil(TestType{45u}) == 64);
164167
}
165168

166169
TEMPLATE_TEST_CASE("bit_floor", "[bit]", std::uint8_t, std::uint16_t,
167170
std::uint32_t, std::uint64_t) {
168171
STATIC_REQUIRE(stdx::bit_floor(TestType{}) == 0);
169172
STATIC_REQUIRE(stdx::bit_floor(TestType{1u}) == 1);
173+
STATIC_REQUIRE(stdx::bit_floor(TestType{3u}) == 2);
174+
STATIC_REQUIRE(stdx::bit_floor(TestType{4u}) == 4);
175+
STATIC_REQUIRE(stdx::bit_floor(TestType{5u}) == 4);
170176
STATIC_REQUIRE(stdx::bit_floor(TestType{45u}) == 32);
171177
}
172178

0 commit comments

Comments
 (0)