Library contents

Kotlin java.lang.Math.unsignedMultiplyHigh

Interpret both long bit patterns as unsigned and return the upper 64 bits of their product.

A simple example

java.lang.Math.unsignedMultiplyHigh

  1. Start with 2 and 3
  2. Do this Read the upper 64 bits of their product
  3. Result 0
The product 6 fits entirely in the lower half of the 128-bit result.
Lesson.kt
fun main() {
    println(java.lang.Math.unsignedMultiplyHigh(2L, 3L))
}
Output
0

Syntax

Kotlin syntax
java.lang.Math.unsignedMultiplyHigh(counter, multiplier)
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Double 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.

From the programval counter = -1L
Result1
Lesson.kt

fun main() {
    val counter = -1L
    val multiplier = 2L
    println(java.lang.Math.unsignedMultiplyHigh(counter, multiplier))
}
Output
1

An all-ones bit pattern represents the largest unsigned 64-bit counter. Doubling it carries one into the high word.

Advertisements

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.

Given4611686018427387904 × 8
Worked result2

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.

Given2305843009213693952 × 16
Worked result2

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.

Documentation for java.lang.Math.unsignedMultiplyHigh