Int128
An exact signed 128-bit integer.
Its job is to hold the result of an operation on Longs that a Long cannot: the product of two of them (timesWide), or a running sum of many. A product of two Longs lies in [−2¹²⁶ + 2⁶³, 2¹²⁶], and its top, 2¹²⁶, needs all 128 signed bits. Up to 2⁶⁴ Long terms cannot sum outside [−2¹²⁷, 2¹²⁷). So comparing two products, or summing Long terms in any order, is exact here, and the only question left is whether the final answer fits back in a Long — which toLongOrNull and divideOrNull answer with null rather than a wrapped value.
Arithmetic between two Int128s (plus, minus) throws ArithmeticException if it leaves 128 bits, and it is never a silent wrap. How near that is depends on what is being summed:
Longterms. It takes more than 2⁶⁴ of them, so a throw is a caller bug rather than a data condition.Products of
Longs. Two are enough.Long.MIN_VALUE.timesWide(Long.MIN_VALUE)is 2¹²⁶, and twice that is 2¹²⁷, one past the largest value. That is the only sum of two products that leaves; the difference of two products always fits; a third term can leave. So a sum of products is a data condition, and a caller whose inputs can reach it bounds them, or the number of terms, before it adds.
The value is two's complement over two words, high · 2⁶⁴ + unsigned(low). Both words are public because a caller keeping a hot accumulator needs to read and rebuild them without allocating; everything else should treat the type as a number.
Identical on every target: it uses only Long operations whose results Kotlin defines the same way on the JVM, Native and wasmJs.
Samples
val a = Long.MAX_VALUE / 3
val b = 7L
val c = Long.MAX_VALUE / 5
val d = 11L
// a/b > c/d exactly when a·d > c·b; both products overflow a Long, neither overflows an Int128.
assertTrue(a.timesWide(d) > c.timesWide(b))
assertTrue(compareProducts(a, d, c, b) > 0)Properties
Functions
this / divisor, rounded as rounding says, or null when the rounded quotient does not fit in a Long.
The exact difference with a Long. Throws ArithmeticException if it leaves 128 bits.
The exact difference. Throws ArithmeticException if it leaves 128 bits.
The exact sum with a Long. Throws ArithmeticException if it leaves 128 bits.
The exact sum. Throws ArithmeticException if it leaves 128 bits.
This value as a Long, or null when it does not fit in one.