Skip to main content
Version: 0.13 (unstable)

Unsigned 256-bit integer operations

Module miden::core::math::u256 contains a set of procedures which can be used to perform unsigned 256-bit integer operations. These operations fall into the following categories:

  • Arithmetic operations - addition, subtraction, multiplication.
  • Comparison operations - equality, equality to zero.
  • Bitwise operations - binary AND, OR, XOR.

A u256 value is represented as a struct with two u128 components:

pub type u256 = struct { hi: u128, lo: u128 }

When placed on the stack, a 256-bit integer is encoded using eight 32-bit limbs (elements). The least-significant limb is assumed to be deeper in the stack. For example, a u256 value consisting of limbs [a7, a6, a5, a4, a3, a2, a1, a0] would be positioned on the stack like so:

[a7, a6, a5, a4, a3, a2, a1, a0, ...]

where a0 is the least significant 32-bit limb and a7 is the most significant.

The procedures in this module assume that the input values are represented using valid 32-bit limbs, but this is not checked. Using invalid inputs may produce undefined results.

Arithmetic operations

ProcedureDescription
wrapping_addPerforms addition of two unsigned 256-bit integers discarding the overflow.

Stack transition: [b7..b0, a7..a0, ...] -> [c7..c0, ...]
where c = (a + b) % 2^256
wrapping_subPerforms subtraction of two unsigned 256-bit integers discarding the underflow.

Stack transition: [b7..b0, a7..a0, ...] -> [c7..c0, ...]
where c = (a - b) % 2^256
wrapping_mulPerforms multiplication of two unsigned 256-bit integers discarding the overflow.

Stack transition: [b7..b0, a7..a0, ...] -> [c7..c0, ...]
where c = (a * b) % 2^256

Comparison operations

ProcedureDescription
eqChecks equality of two unsigned 256-bit integers.

Stack transition: [b7..b0, a7..a0, ...] -> [c, ...]
where c = 1 when a == b, and 0 otherwise.
eqzChecks if an unsigned 256-bit integer equals zero.

Stack transition: [a7..a0, ...] -> [c, ...]
where c = 1 when a == 0, and 0 otherwise.

Bitwise operations

ProcedureDescription
andPerforms bitwise AND of two unsigned 256-bit integers.

Stack transition: [b7..b0, a7..a0, ...] -> [c7..c0, ...]
where c = a AND b
orPerforms bitwise OR of two unsigned 256-bit integers.

Stack transition: [b7..b0, a7..a0, ...] -> [c7..c0, ...]
where c = a OR b
xorPerforms bitwise XOR of two unsigned 256-bit integers.

Stack transition: [b7..b0, a7..a0, ...] -> [c7..c0, ...]
where c = a XOR b