Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Optimize bit_ceil to use constant-time bitwise implementation #187

Copy link
Copy link
Open
@avighnac

Description

@avighnac
Issue body actions

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.

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

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.