Skip to content

Optimize bit_ceil to use constant-time bitwise implementation #187

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

Open
avighnac opened this issue May 15, 2025 · 0 comments
Open

Optimize bit_ceil to use constant-time bitwise implementation #187

avighnac opened this issue May 15, 2025 · 0 comments

Comments

@avighnac
Copy link

Currently, the bit_ceil function is implemented as:

unsigned int bit_ceil(unsigned int n) {
    unsigned int x = 1;
    while (x < (unsigned int)(n)) x *= 2;
    return x;
}

This works correctly, but it uses a loop and can take up to log(n) iterations. It can be rewritten in constant time using standard bit-twiddling techniques, which are generally more efficient and can compile down to ~5 instructions.

Suggested optimized implementation:

unsigned int bit_ceil(unsigned int n) {
    if (n == 0) return 1;
    n--;
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    return n + 1;
}

This implementation:

  • Avoids the loop entirely
  • Works in constant time for all 32-bit unsigned integers

It would be great to update the function to this version for better performance.

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

1 participant