Java Math.unsignedMultiplyHigh
Interpret both long bit patterns as unsigned and return the upper 64 bits of their product.
A simple example
Math.unsignedMultiplyHigh
- Start with 2 and 3
- Do this Read the upper 64 bits of their product
- Result 0
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.unsignedMultiplyHigh(2L, 3L));
}
}
0
Syntax
Math.unsignedMultiplyHigh(counter, multiplier)
JDK 21 method signatures (1)
public static long unsignedMultiplyHigh(long x, long y)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaDouble a device counter stored as unsigned bits
A device transmits a counter as a fixed-width bit pattern. When scaling or multiplying that value, the reader must keep track of which part of the wider result belongs in the stored field.
class Main {
public static void main(String[] args) throws Exception {
long counter = -1L;
long multiplier = 2L;
System.out.println(Math.unsignedMultiplyHigh(counter, multiplier));
}
}
1
An all-ones bit pattern represents the largest unsigned 64-bit counter. Doubling it carries one into the high word.
Keep the upper word of a packet counter
A packet counter stores a large total in two 64-bit words. Its decoder applies an eightfold counter scale and needs the upper word of the exact product.
Divide the full nonnegative product by 2⁶⁴ and keep its integer quotient.
Keep the upper word of a storage meter
A storage meter stores a large total in two 64-bit words. Its decoder applies a sixteenfold counter scale and needs the upper word of the exact product.
Divide the full nonnegative product by 2⁶⁴ and keep its integer quotient.
What to watch for
A negative Java long can represent an unsigned bit pattern. Keep the interpretation consistent when displaying it.