Scala java.lang.Math.multiplyHigh
Return the high 64 bits of a signed 128-bit product represented by two long inputs.
A simple example
java.lang.Math.multiplyHigh
- Start with 2 and 3
- Do this Read the upper 64 bits of their product
- Result 0
object Lesson extends App {
println(java.lang.Math.multiplyHigh(2L, 3L))
}
0
Syntax
java.lang.Math.multiplyHigh(units, factor)
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonKeep the high word of a large meter total
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.
object Lesson {
def main(args: Array[String]): Unit = {
val units = 4611686018427387904L
val factor = 4L
println(java.lang.Math.multiplyHigh(units, factor))
}
}
1
Multiplying two to the power of 62 by four produces two to the power of 64. Its high word is one and its low word is zero.
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
The high word alone is only part of the product. Use BigInteger when you need the full decimal value.