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

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

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P4 P4
    • 14
    • 14
    • hotspot
    • None
    • b27

      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.

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

              Created:
              Updated:
              Resolved: