Skip to content

Optimize bit_ceil to use constant-time bitwise implementation #187

Description

@avighnac

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions