Skip to content

Commit 183fc37

Browse files
committed
Change nextPowOfTwo
1 parent 1055f81 commit 183fc37

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

internal-api/src/main/java/datadog/trace/util/BitUtils.java

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,24 @@ private BitUtils() {}
1111
* @return the next power of two ≥ {@code value}
1212
*/
1313
public static int nextPowerOfTwo(int value) {
14+
// The next power of two for 0 or 1 is 1.
1415
if (value <= 1) {
1516
return 1;
1617
}
1718

18-
// Round up to next power of two (bitwise equivalent of using log2 and pow again)
19-
value--;
20-
value |= value >> 1;
21-
value |= value >> 2;
22-
value |= value >> 4;
23-
value |= value >> 8;
24-
value |= value >> 16;
25-
value++;
19+
// Compute how many leading zero bits there are in (value - 1). This gives us information about
20+
// where the highest set bit is.
21+
int n = Integer.numberOfLeadingZeros(value - 1);
2622

27-
// handle overflow (e.g., if value was already near Integer.MAX_VALUE)
28-
if (value <= 0) {
29-
return 1 << 30; // max power of two that fits in int
23+
// -1 in two's complement = 0xFFFF_FFFF (all bits set to 1). Unsigned right-shifting by n: (-1
24+
// >>> n) produces a mask of (32 - n) one-bits.
25+
int result = (-1 >>> n) + 1;
26+
27+
// If result overflowed clamp it to the largest unsigned power of two fitting an int.
28+
if (result <= 0) {
29+
return 1 << 30;
3030
}
3131

32-
return value;
32+
return result;
3333
}
3434
}

0 commit comments

Comments
 (0)