Pelago
Core typesPrimitive types

int128

The 128-bit signed integer: range, literals, checked arithmetic, methods, conversions and JSON.

int128 is a 128-bit two's complement integer, stored as 2 64-bit words, least significant first. Its values run from -170141183460469231731687303715884105728 to 170141183460469231731687303715884105727. It follows exactly the rules of int with a wider range, so there is nothing new to learn.

Writing a value

A decimal, hexadecimal, binary or octal literal that fits the type, such as const a: int128 = 170141183460469231731687303715884105727. A literal outside the range is a compile-time error.

Arithmetic

+ - * / %, ++, --, the bitwise operators, <<, >>, the wrapping forms +% -% *%, the comparisons and every op= form work on two values of int128.

  • Overflow stops the program with stopped: arithmetic overflow; so does a division by zero (stopped: division by zero) and a shift by 128 or more (stopped: shifted by the width or more).
  • The wrapping forms wrap modulo 2^128.
  • Two different integer types are never mixed silently.
fn main() {
    const lo: int128 = -170141183460469231731687303715884105728
    const hi: int128 = 170141183460469231731687303715884105727
    print("#lo")
    print("#hi")
    print("#(hi +% 1) #(hi / 3) #(hi % 1000) #(hi >> 100) #(hi & 255)")
    var f: int128 = 1
    var i: int128 = 1
    while i <= 25 {
        f = f * i
        i += 1
    }
    print("25! = #f")
}
-170141183460469231731687303715884105728
170141183460469231731687303715884105727
-170141183460469231731687303715884105728 56713727820156410577229101238628035242 727 134217727 255
25! = 15511210043330985984000000

Overflow is a stop:

fn main() {
    const top: int128 = 170141183460469231731687303715884105727
    print(top + 1)
}
stopped: arithmetic overflow

Methods

abs(), min(o), max(o) and pow(e). Like every other operation, pow stops the program on overflow. Everything else is an operator.

Converting

to converts when nothing can be lost. From int128, to is accepted for: int256, float. to float rounds to within one step in the last place. Into int128, a narrower type of the same signedness, or a narrower unsigned type into a signed one, is accepted. Converting down, and float to a wide integer, are not written yet.

Equality, hashing and JSON

A int128 is eq, order, hash and show, so it works as a map key, a set member, a struct field and in for ranges and switch patterns. With @derive(toJson) it is written as a JSON string of digits, because most JSON tools read numbers as 64-bit floats; reading accepts the string, and a plain JSON number when it fits int. A value outside the range is an error, never a wrap. See typed JSON.

Not finished

Speed: correctness came first, so division is a shift-and-subtract loop and printing a large value is slow. Narrowing to, and float to a wide integer, are not written yet.

int, Wide integers overview

On this page