Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8234331

Add robust and optimized utility for rounding up to next power of two

    XMLWordPrintable

    Details

    • Type: Enhancement
    • Status: Resolved
    • Priority: P4
    • Resolution: Fixed
    • Affects Version/s: 14
    • Fix Version/s: 14
    • Component/s: hotspot
    • Labels:
      None
    • Subcomponent:
    • Resolved In Build:
      b27

      Description

      In various places we have code that does the equivalent of

      do_something(uint x) {
        uint next_pow2 = 1;
        while (next_pow2 < x) {
          next_pow2 <<= 1;
        }
        ...
      }

      This is brittle (would loop forever if x > (1 << 31)) and also somewhat inefficient. Adding a utility that does the equivalent of

      if (x == 0) {
        next_pow2 = 1;
      } else if (x < (1 << 31)) {
        next_pow2 = 1U << (32 - count_leading_zeros(x));
      } else {
        next_pow2 = uint_max; // might need to be able to allow different behaviors here

      might avoid infinite loops at the extreme (although it's debatable what should be returned when x > 2^31) and potentially be more efficient.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              redestad Claes Redestad
              Reporter:
              redestad Claes Redestad
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: