Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

best::count_zeros doesn't handle integer promotion properly #27

Open
sarah-quinones opened this issue Jul 18, 2024 · 2 comments
Open

best::count_zeros doesn't handle integer promotion properly #27

sarah-quinones opened this issue Jul 18, 2024 · 2 comments

Comments

@sarah-quinones
Copy link

it currently returns

return std::popcount(~to_unsigned(x));

when x is smaller than int, e.g., short. to_unsigned(x) returns a value of type unsigned short. using it as an operand of an arithmetic operation ~x, it first gets promoted to int, then the operation gets applied, returning another int, which causes the call to std::popcount to fail since it's a signed integer type.

to fix this we could write it as

auto u = to_unsigned(x);
using unsigned = decltype(u);

return std::popcount(static_cast<unsigned>(~u));
@mcy
Copy link
Owner

mcy commented Jul 22, 2024

I think the easiest fix is gonna be std::popcount(to_unsigned(~to_unsigned(x)). Casting to unsigned isn't correct because it won't work right for 64-bit arguments. Feel free to file a pull request here.

@sarah-quinones
Copy link
Author

oh oops. i haven't written c++ in a while so i forgot unsigned is a keyword 💀
the unsigned in the cast refers to the type alias on the second line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants