Primitive Type u128
1.26.0
Expand description
Source§
1.43.0 · Source
The smallest value that can be represented by this integer type.
§Examples
assert_eq!(u128::MIN, 0);1.43.0 · Source
The largest value that can be represented by this integer type (2128 − 1).
§Examples
assert_eq!(u128::MAX, 340282366920938463463374607431768211455);1.0.0 (const: 1.32.0) · Source
Returns the number of ones in the binary representation of self.
§Examples
let n = 0b01001100u128;
assert_eq!(n.count_ones(), 3);
let max = u128::MAX;
assert_eq!(max.count_ones(), 128);
let zero = 0u128;
assert_eq!(zero.count_ones(), 0);1.0.0 (const: 1.32.0) · Source
Returns the number of zeros in the binary representation of self.
§Examples
let zero = 0u128;
assert_eq!(zero.count_zeros(), 128);
let max = u128::MAX;
assert_eq!(max.count_zeros(), 0);1.0.0 (const: 1.32.0) · Source
Returns the number of leading zeros in the binary representation of self.
Depending on what you’re doing with the value, you might also be interested in the
ilog2 function which returns a consistent number, even if the type widens.
§Examples
let n = u128::MAX >> 2;
assert_eq!(n.leading_zeros(), 2);
let zero = 0u128;
assert_eq!(zero.leading_zeros(), 128);
let max = u128::MAX;
assert_eq!(max.leading_zeros(), 0);1.0.0 (const: 1.32.0) · Source
Returns the number of trailing zeros in the binary representation
of self.
§Examples
let n = 0b0101000u128;
assert_eq!(n.trailing_zeros(), 3);
let zero = 0u128;
assert_eq!(zero.trailing_zeros(), 128);
let max = u128::MAX;
assert_eq!(max.trailing_zeros(), 0);1.46.0 (const: 1.46.0) · Source
Returns the number of leading ones in the binary representation of self.
§Examples
let n = !(u128::MAX >> 2);
assert_eq!(n.leading_ones(), 2);
let zero = 0u128;
assert_eq!(zero.leading_ones(), 0);
let max = u128::MAX;
assert_eq!(max.leading_ones(), 128);1.46.0 (const: 1.46.0) · Source
Returns the number of trailing ones in the binary representation
of self.
§Examples
let n = 0b1010111u128;
assert_eq!(n.trailing_ones(), 3);
let zero = 0u128;
assert_eq!(zero.trailing_ones(), 0);
let max = u128::MAX;
assert_eq!(max.trailing_ones(), 128);Source 🔬This is a nightly-only experimental API. (uint_bit_width #142326)
uint_bit_width #142326)Returns the minimum number of bits required to represent self.
This method returns zero if self is zero.
§Examples
#![feature(uint_bit_width)]
assert_eq!(0_u128.bit_width(), 0);
assert_eq!(0b111_u128.bit_width(), 3);
assert_eq!(0b1110_u128.bit_width(), 4);
assert_eq!(u128::MAX.bit_width(), 128);Source 🔬This is a nightly-only experimental API. (isolate_most_least_significant_one #136909)
isolate_most_least_significant_one #136909)Returns self with only the most significant bit set, or 0 if
the input is 0.
§Examples
#![feature(isolate_most_least_significant_one)]
let n: u128 = 0b_01100100;
assert_eq!(n.isolate_highest_one(), 0b_01000000);
assert_eq!(0_u128.isolate_highest_one(), 0);Source 🔬This is a nightly-only experimental API. (isolate_most_least_significant_one #136909)
isolate_most_least_significant_one #136909)Returns self with only the least significant bit set, or 0 if
the input is 0.
§Examples
#![feature(isolate_most_least_significant_one)]
let n: u128 = 0b_01100100;
assert_eq!(n.isolate_lowest_one(), 0b_00000100);
assert_eq!(0_u128.isolate_lowest_one(), 0);Source 🔬This is a nightly-only experimental API. (int_lowest_highest_one #145203)
int_lowest_highest_one #145203)Returns the index of the highest bit set to one in self, or None
if self is 0.
§Examples
#![feature(int_lowest_highest_one)]
assert_eq!(0b0_u128.highest_one(), None);
assert_eq!(0b1_u128.highest_one(), Some(0));
assert_eq!(0b1_0000_u128.highest_one(), Some(4));
assert_eq!(0b1_1111_u128.highest_one(), Some(4));Source 🔬This is a nightly-only experimental API. (int_lowest_highest_one #145203)
int_lowest_highest_one #145203)Returns the index of the lowest bit set to one in self, or None
if self is 0.
§Examples
#![feature(int_lowest_highest_one)]
assert_eq!(0b0_u128.lowest_one(), None);
assert_eq!(0b1_u128.lowest_one(), Some(0));
assert_eq!(0b1_0000_u128.lowest_one(), Some(4));
assert_eq!(0b1_1111_u128.lowest_one(), Some(0));1.87.0 (const: 1.87.0) · Source
Returns the bit pattern of self reinterpreted as a signed integer of the same size.
This produces the same result as an as cast, but ensures that the bit-width remains
the same.
§Examples
let n = u128::MAX;
assert_eq!(n.cast_signed(), -1i128);1.0.0 (const: 1.32.0) · Source
Shifts the bits to the left by a specified amount, n,
wrapping the truncated bits to the end of the resulting integer.
rotate_left(n) is equivalent to applying rotate_left(1) a total of n times. In
particular, a rotation by the number of bits in self returns the input value
unchanged.
Please note this isn’t the same operation as the << shifting operator!
§Examples
let n = 0x13f40000000000000000000000004f76u128;
let m = 0x4f7613f4;
assert_eq!(n.rotate_left(16), m);
assert_eq!(n.rotate_left(1024), n);1.0.0 (const: 1.32.0) · Source
Shifts the bits to the right by a specified amount, n,
wrapping the truncated bits to the beginning of the resulting
integer.
rotate_right(n) is equivalent to applying rotate_right(1) a total of n times. In
particular, a rotation by the number of bits in self returns the input value
unchanged.
Please note this isn’t the same operation as the >> shifting operator!
§Examples
let n = 0x4f7613f4u128;
let m = 0x13f40000000000000000000000004f76;
assert_eq!(n.rotate_right(16), m);
assert_eq!(n.rotate_right(1024), n);Source 🔬This is a nightly-only experimental API. (funnel_shifts #145686)
funnel_shifts #145686)Performs a left funnel shift (concatenates self with rhs, with self
making up the most significant half, then shifts the combined value left
by n, and most significant half is extracted to produce the result).
Please note this isn’t the same operation as the << shifting operator or
rotate_left, although a.funnel_shl(a, n) is equivalent
to a.rotate_left(n).
§Panics
If n is greater than or equal to the number of bits in self
§Examples
Basic usage:
#![feature(funnel_shifts)]
let a = 0x13f40000000000000000000000004f76u128;
let b = 0x2fe78e45983acd98039000008736273u128;
let m = 0x4f7602fe;
assert_eq!(a.funnel_shl(b, 16), m);Source 🔬This is a nightly-only experimental API. (funnel_shifts #145686)
funnel_shifts #145686)Performs a right funnel shift (concatenates self and rhs, with self
making up the most significant half, then shifts the combined value right
by n, and least significant half is extracted to produce the result).
Please note this isn’t the same operation as the >> shifting operator or
rotate_right, although a.funnel_shr(a, n) is equivalent
to a.rotate_right(n).
§Panics
If n is greater than or equal to the number of bits in self
§Examples
Basic usage:
#![feature(funnel_shifts)]
let a = 0x13f40000000000000000000000004f76u128;
let b = 0x2fe78e45983acd98039000008736273u128;
let m = 0x4f7602fe78e45983acd9803900000873;
assert_eq!(a.funnel_shr(b, 16), m);1.0.0 (const: 1.32.0) · Source
Reverses the byte order of the integer.
§Examples
let n = 0x12345678901234567890123456789012u128;
let m = n.swap_bytes();
assert_eq!(m, 0x12907856341290785634129078563412);Source 🔬This is a nightly-only experimental API. (uint_gather_scatter_bits #149069)
uint_gather_scatter_bits #149069)Returns an integer with the bit locations specified by mask packed
contiguously into the least significant bits of the result.
#![feature(uint_gather_scatter_bits)]
let n: u128 = 0b1011_1100;
assert_eq!(n.gather_bits(0b0010_0100), 0b0000_0011);
assert_eq!(n.gather_bits(0xF0), 0b0000_1011);Source 🔬This is a nightly-only experimental API. (uint_gather_scatter_bits #149069)
uint_gather_scatter_bits #149069)Returns an integer with the least significant bits of self
distributed to the bit locations specified by mask.
#![feature(uint_gather_scatter_bits)]
let n: u128 = 0b1010_1101;
assert_eq!(n.scatter_bits(0b0101_0101), 0b0101_0001);
assert_eq!(n.scatter_bits(0xF0), 0b1101_0000);1.37.0 (const: 1.37.0) · Source
Reverses the order of bits in the integer. The least significant bit becomes the most significant bit, second least-significant bit becomes second most-significant bit, etc.
§Examples
let n = 0x12345678901234567890123456789012u128;
let m = n.reverse_bits();
assert_eq!(m, 0x48091e6a2c48091e6a2c48091e6a2c48);
assert_eq!(0, 0u128.reverse_bits());1.0.0 (const: 1.32.0) · Source
Converts an integer from big endian to the target’s endianness.
On big endian this is a no-op. On little endian the bytes are swapped.
§Examples
let n = 0x1Au128;
if cfg!(target_endian = "big") {
assert_eq!(u128::from_be(n), n)
} else {
assert_eq!(u128::from_be(n), n.swap_bytes())
}1.0.0 (const: 1.32.0) · Source
Converts an integer from little endian to the target’s endianness.
On little endian this is a no-op. On big endian the bytes are swapped.
§Examples
let n = 0x1Au128;
if cfg!(target_endian = "little") {
assert_eq!(u128::from_le(n), n)
} else {
assert_eq!(u128::from_le(n), n.swap_bytes())
}1.0.0 (const: 1.32.0) · Source
Converts self to big endian from the target’s endianness.
On big endian this is a no-op. On little endian the bytes are swapped.
§Examples
let n = 0x1Au128;
if cfg!(target_endian = "big") {
assert_eq!(n.to_be(), n)
} else {
assert_eq!(n.to_be(), n.swap_bytes())
}1.0.0 (const: 1.32.0) · Source
Converts self to little endian from the target’s endianness.
On little endian this is a no-op. On big endian the bytes are swapped.
§Examples
let n = 0x1Au128;
if cfg!(target_endian = "little") {
assert_eq!(n.to_le(), n)
} else {
assert_eq!(n.to_le(), n.swap_bytes())
}1.0.0 (const: 1.47.0) · Source
Checked integer addition. Computes self + rhs, returning None
if overflow occurred.
§Examples
assert_eq!((u128::MAX - 2).checked_add(1), Some(u128::MAX - 1));
assert_eq!((u128::MAX - 2).checked_add(3), None);1.91.0 (const: 1.91.0) · Source
Strict integer addition. Computes self + rhs, panicking
if overflow occurred.
§Panics
§Overflow behavior
This function will always panic on overflow, regardless of whether overflow checks are enabled.
§Examples
assert_eq!((u128::MAX - 2).strict_add(1), u128::MAX - 1);The following panics because of overflow:
let _ = (u128::MAX - 2).strict_add(3);1.79.0 (const: 1.79.0) · Source
Unchecked integer addition. Computes self + rhs, assuming overflow
cannot occur.
Calling x.unchecked_add(y) is semantically equivalent to calling
x.checked_add(y).unwrap_unchecked().
If you’re just trying to avoid the panic in debug mode, then do not
use this. Instead, you’re looking for wrapping_add.
§Safety
This results in undefined behavior when
self + rhs > u128::MAX or self + rhs < u128::MIN,
i.e. when checked_add would return None.
1.66.0 (const: 1.66.0) · Source
Checked addition with a signed integer. Computes self + rhs,
returning None if overflow occurred.
§Examples
assert_eq!(1u128.checked_add_signed(2), Some(3));
assert_eq!(1u128.checked_add_signed(-2), None);
assert_eq!((u128::MAX - 2).checked_add_signed(3), None);1.91.0 (const: 1.91.0) · Source
Strict addition with a signed integer. Computes self + rhs,
panicking if overflow occurred.
§Panics
§Overflow behavior
This function will always panic on overflow, regardless of whether overflow checks are enabled.
§Examples
assert_eq!(1u128.strict_add_signed(2), 3);The following panic because of overflow:
let _ = 1u128.strict_add_signed(-2);let _ = (u128::MAX - 2).strict_add_signed(3);1.0.0 (const: 1.47.0) · Source
Checked integer subtraction. Computes self - rhs, returning
None if overflow occurred.
§Examples
assert_eq!(1u128.checked_sub(1), Some(0));
assert_eq!(0u128.checked_sub(1), None);1.91.0 (const: 1.91.0) · Source
Strict integer subtraction. Computes self - rhs, panicking if
overflow occurred.
§Panics
§Overflow behavior
This function will always panic on overflow, regardless of whether overflow checks are enabled.
§Examples
assert_eq!(1u128.strict_sub(1), 0);The following panics because of overflow:
let _ = 0u128.strict_sub(1);1.79.0 (const: 1.79.0) · Source
Unchecked integer subtraction. Computes self - rhs, assuming overflow
cannot occur.
Calling x.unchecked_sub(y) is semantically equivalent to calling
x.checked_sub(y).unwrap_unchecked().
If you’re just trying to avoid the panic in debug mode, then do not
use this. Instead, you’re looking for wrapping_sub.
If you find yourself writing code like this:
if foo >= bar {
// SAFETY: just checked it will not overflow
let diff = unsafe { foo.unchecked_sub(bar) };
// ... use diff ...
}Consider changing it to
if let Some(diff) = foo.checked_sub(bar) {
// ... use diff ...
}As that does exactly the same thing – including telling the optimizer
that the subtraction cannot overflow – but avoids needing unsafe.
§Safety
This results in undefined behavior when
self - rhs > u128::MAX or self - rhs < u128::MIN,
i.e. when checked_sub would return None.
1.90.0 (const: 1.90.0) · Source
Checked subtraction with a signed integer. Computes self - rhs,
returning None if overflow occurred.
§Examples
assert_eq!(1u128.checked_sub_signed(2), None);
assert_eq!(1u128.checked_sub_signed(-2), Some(3));
assert_eq!((u128::MAX - 2).checked_sub_signed(-4), None);1.91.0 (const: 1.91.0) · Source
Strict subtraction with a signed integer. Computes self - rhs,
panicking if overflow occurred.
§Panics
§Overflow behavior
This function will always panic on overflow, regardless of whether overflow checks are enabled.
§Examples
assert_eq!(3u128.strict_sub_signed(2), 1);The following panic because of overflow:
let _ = 1u128.strict_sub_signed(2);let _ = (u128::MAX).strict_sub_signed(-1);1.91.0 (const: 1.91.0) · Source
Checked integer subtraction. Computes self - rhs and checks if the result fits into an i128, returning None if overflow occurred.
§Examples
assert_eq!(10u128.checked_signed_diff(2), Some(8));
assert_eq!(2u128.checked_signed_diff(10), Some(-8));
assert_eq!(u128::MAX.checked_signed_diff(i128::MAX as u128), None);
assert_eq!((i128::MAX as u128).checked_signed_diff(u128::MAX), Some(i128::MIN));
assert_eq!((i128::MAX as u128 + 1).checked_signed_diff(0), None);
assert_eq!(u128::MAX.checked_signed_diff(u128::MAX), Some(0));1.0.0 (const: 1.47.0) · Source
Checked integer multiplication. Computes self * rhs, returning
None if overflow occurred.
§Examples
assert_eq!(5u128.checked_mul(1), Some(5));
assert_eq!(u128::MAX.checked_mul(2), None);1.91.0 (const: 1.91.0) · Source
Strict integer multiplication. Computes self * rhs, panicking if
overflow occurred.
§Panics
§Overflow behavior
This function will always panic on overflow, regardless of whether overflow checks are enabled.
§Examples
assert_eq!(5u128.strict_mul(1), 5);The following panics because of overflow:
let _ = u128::MAX.strict_mul(2);1.79.0 (const: 1.79.0) · Source
Unchecked integer multiplication. Computes self * rhs, assuming overflow
cannot occur.
Calling x.unchecked_mul(y) is semantically equivalent to calling
x.checked_mul(y).unwrap_unchecked().
If you’re just trying to avoid the panic in debug mode, then do not
use this. Instead, you’re looking for wrapping_mul.
§Safety
This results in undefined behavior when
self * rhs > u128::MAX or self * rhs < u128::MIN,
i.e. when checked_mul would return None.
1.0.0 (const: 1.52.0) · Source
Checked integer division. Computes self / rhs, returning None
if rhs == 0.
§Examples
assert_eq!(128u128.checked_div(2), Some(64));
assert_eq!(1u128.checked_div(0), None);1.91.0 (const: 1.91.0) · Source
Strict integer division. Computes self / rhs.
Strict division on unsigned types is just normal division. There’s no way overflow could ever happen. This function exists so that all operations are accounted for in the strict operations.
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(100u128.strict_div(10), 10);The following panics because of division by zero:
let _ = (1u128).strict_div(0);1.38.0 (const: 1.52.0) · Source
Checked Euclidean division. Computes self.div_euclid(rhs), returning None
if rhs == 0.
§Examples
assert_eq!(128u128.checked_div_euclid(2), Some(64));
assert_eq!(1u128.checked_div_euclid(0), None);1.91.0 (const: 1.91.0) · Source
Strict Euclidean division. Computes self.div_euclid(rhs).
Strict division on unsigned types is just normal division. There’s no
way overflow could ever happen. This function exists so that all
operations are accounted for in the strict operations. Since, for the
positive integers, all common definitions of division are equal, this
is exactly equal to self.strict_div(rhs).
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(100u128.strict_div_euclid(10), 10);The following panics because of division by zero:
let _ = (1u128).strict_div_euclid(0);Source 🔬This is a nightly-only experimental API. (exact_div #139911)
exact_div #139911)Checked integer division without remainder. Computes self / rhs,
returning None if rhs == 0 or if self % rhs != 0.
§Examples
#![feature(exact_div)]
assert_eq!(64u128.checked_div_exact(2), Some(32));
assert_eq!(64u128.checked_div_exact(32), Some(2));
assert_eq!(64u128.checked_div_exact(0), None);
assert_eq!(65u128.checked_div_exact(2), None);Source 🔬This is a nightly-only experimental API. (exact_div #139911)
exact_div #139911)Unchecked integer division without remainder. Computes self / rhs.
§Safety
This results in undefined behavior when rhs == 0 or self % rhs != 0,
i.e. when checked_div_exact would return None.
1.7.0 (const: 1.52.0) · Source
Checked integer remainder. Computes self % rhs, returning None
if rhs == 0.
§Examples
assert_eq!(5u128.checked_rem(2), Some(1));
assert_eq!(5u128.checked_rem(0), None);1.91.0 (const: 1.91.0) · Source
Strict integer remainder. Computes self % rhs.
Strict remainder calculation on unsigned types is just the regular remainder calculation. There’s no way overflow could ever happen. This function exists so that all operations are accounted for in the strict operations.
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(100u128.strict_rem(10), 0);The following panics because of division by zero:
let _ = 5u128.strict_rem(0);1.38.0 (const: 1.52.0) · Source
Checked Euclidean modulo. Computes self.rem_euclid(rhs), returning None
if rhs == 0.
§Examples
assert_eq!(5u128.checked_rem_euclid(2), Some(1));
assert_eq!(5u128.checked_rem_euclid(0), None);1.91.0 (const: 1.91.0) · Source
Strict Euclidean modulo. Computes self.rem_euclid(rhs).
Strict modulo calculation on unsigned types is just the regular
remainder calculation. There’s no way overflow could ever happen.
This function exists so that all operations are accounted for in the
strict operations. Since, for the positive integers, all common
definitions of division are equal, this is exactly equal to
self.strict_rem(rhs).
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(100u128.strict_rem_euclid(10), 0);The following panics because of division by zero:
let _ = 5u128.strict_rem_euclid(0);Source 🔬This is a nightly-only experimental API. (disjoint_bitor #135758)
disjoint_bitor #135758)Same value as self | other, but UB if any bit position is set in both inputs.
This is a situational micro-optimization for places where you’d rather
use addition on some platforms and bitwise or on other platforms, based
on exactly which instructions combine better with whatever else you’re
doing. Note that there’s no reason to bother using this for places
where it’s clear from the operations involved that they can’t overlap.
For example, if you’re combining u16s into a u32 with
((a as u32) << 16) | (b as u32), that’s fine, as the backend will
know those sides of the | are disjoint without needing help.
§Examples
#![feature(disjoint_bitor)]
// SAFETY: `1` and `4` have no bits in common.
unsafe {
assert_eq!(1_u128.unchecked_disjoint_bitor(4), 5);
}§Safety
Requires that (self & other) == 0, otherwise it’s immediate UB.
Equivalently, requires that (self | other) == (self + other).
1.67.0 (const: 1.67.0) · Source
Returns the logarithm of the number with respect to an arbitrary base, rounded down.
This method might not be optimized owing to implementation details;
ilog2 can produce results more efficiently for base 2, and ilog10
can produce results more efficiently for base 10.
§Panics
This function will panic if self is zero, or if base is less than 2.
§Examples
assert_eq!(5u128.ilog(5), 1);1.67.0 (const: 1.67.0) · Source
1.67.0 (const: 1.67.0) · Source
1.67.0 (const: 1.67.0) · Source
Returns the logarithm of the number with respect to an arbitrary base, rounded down.
Returns None if the number is zero, or if the base is not at least 2.
This method might not be optimized owing to implementation details;
checked_ilog2 can produce results more efficiently for base 2, and
checked_ilog10 can produce results more efficiently for base 10.
§Examples
assert_eq!(5u128.checked_ilog(5), Some(1));1.67.0 (const: 1.67.0) · Source
Returns the base 2 logarithm of the number, rounded down.
Returns None if the number is zero.
§Examples
assert_eq!(2u128.checked_ilog2(), Some(1));1.67.0 (const: 1.67.0) · Source
Returns the base 10 logarithm of the number, rounded down.
Returns None if the number is zero.
§Examples
assert_eq!(10u128.checked_ilog10(), Some(1));1.7.0 (const: 1.47.0) · Source
Checked negation. Computes -self, returning None unless self == 0.
Note that negating any positive integer will overflow.
§Examples
assert_eq!(0u128.checked_neg(), Some(0));
assert_eq!(1u128.checked_neg(), None);1.91.0 (const: 1.91.0) · Source
Strict negation. Computes -self, panicking unless self == 0.
Note that negating any positive integer will overflow.
§Panics
§Overflow behavior
This function will always panic on overflow, regardless of whether overflow checks are enabled.
§Examples
assert_eq!(0u128.strict_neg(), 0);The following panics because of overflow:
let _ = 1u128.strict_neg();1.7.0 (const: 1.47.0) · Source
Checked shift left. Computes self << rhs, returning None
if rhs is larger than or equal to the number of bits in self.
§Examples
assert_eq!(0x1u128.checked_shl(4), Some(0x10));
assert_eq!(0x10u128.checked_shl(129), None);
assert_eq!(0x10u128.checked_shl(127), Some(0));1.91.0 (const: 1.91.0) · Source
Strict shift left. Computes self << rhs, panicking if rhs is larger
than or equal to the number of bits in self.
§Panics
§Overflow behavior
This function will always panic on overflow, regardless of whether overflow checks are enabled.
§Examples
assert_eq!(0x1u128.strict_shl(4), 0x10);The following panics because of overflow:
let _ = 0x10u128.strict_shl(129);1.93.0 (const: 1.93.0) · Source
Unchecked shift left. Computes self << rhs, assuming that
rhs is less than the number of bits in self.
§Safety
This results in undefined behavior if rhs is larger than
or equal to the number of bits in self,
i.e. when checked_shl would return None.
1.87.0 (const: 1.87.0) · Source
Unbounded shift left. Computes self << rhs, without bounding the value of rhs.
If rhs is larger or equal to the number of bits in self,
the entire value is shifted out, and 0 is returned.
§Examples
assert_eq!(0x1u128.unbounded_shl(4), 0x10);
assert_eq!(0x1u128.unbounded_shl(129), 0);Source 🔬This is a nightly-only experimental API. (exact_bitshifts #144336)
exact_bitshifts #144336)Exact shift left. Computes self << rhs as long as it can be reversed losslessly.
Returns None if any non-zero bits would be shifted out or if rhs >=
u128::BITS.
Otherwise, returns Some(self << rhs).
§Examples
#![feature(exact_bitshifts)]
assert_eq!(0x1u128.shl_exact(4), Some(0x10));
assert_eq!(0x1u128.shl_exact(129), None);Source 🔬This is a nightly-only experimental API. (exact_bitshifts #144336)
exact_bitshifts #144336)Unchecked exact shift left. Computes self << rhs, assuming the operation can be
losslessly reversed rhs cannot be larger than
u128::BITS.
§Safety
This results in undefined behavior when rhs > self.leading_zeros() || rhs >= u128::BITS
i.e. when
u128::shl_exact
would return None.
1.7.0 (const: 1.47.0) · Source
Checked shift right. Computes self >> rhs, returning None
if rhs is larger than or equal to the number of bits in self.
§Examples
assert_eq!(0x10u128.checked_shr(4), Some(0x1));
assert_eq!(0x10u128.checked_shr(129), None);1.91.0 (const: 1.91.0) · Source
Strict shift right. Computes self >> rhs, panicking if rhs is
larger than or equal to the number of bits in self.
§Panics
§Overflow behavior
This function will always panic on overflow, regardless of whether overflow checks are enabled.
§Examples
assert_eq!(0x10u128.strict_shr(4), 0x1);The following panics because of overflow:
let _ = 0x10u128.strict_shr(129);1.93.0 (const: 1.93.0) · Source
Unchecked shift right. Computes self >> rhs, assuming that
rhs is less than the number of bits in self.
§Safety
This results in undefined behavior if rhs is larger than
or equal to the number of bits in self,
i.e. when checked_shr would return None.
1.87.0 (const: 1.87.0) · Source
Unbounded shift right. Computes self >> rhs, without bounding the value of rhs.
If rhs is larger or equal to the number of bits in self,
the entire value is shifted out, and 0 is returned.
§Examples
assert_eq!(0x10u128.unbounded_shr(4), 0x1);
assert_eq!(0x10u128.unbounded_shr(129), 0);Source 🔬This is a nightly-only experimental API. (exact_bitshifts #144336)
exact_bitshifts #144336)Exact shift right. Computes self >> rhs as long as it can be reversed losslessly.
Returns None if any non-zero bits would be shifted out or if rhs >=
u128::BITS.
Otherwise, returns Some(self >> rhs).
§Examples
#![feature(exact_bitshifts)]
assert_eq!(0x10u128.shr_exact(4), Some(0x1));
assert_eq!(0x10u128.shr_exact(5), None);Source 🔬This is a nightly-only experimental API. (exact_bitshifts #144336)
exact_bitshifts #144336)Unchecked exact shift right. Computes self >> rhs, assuming the operation can be
losslessly reversed and rhs cannot be larger than
u128::BITS.
§Safety
This results in undefined behavior when rhs > self.trailing_zeros() || rhs >= u128::BITS
i.e. when
u128::shr_exact
would return None.
1.34.0 (const: 1.50.0) · Source
Checked exponentiation. Computes self.pow(exp), returning None if
overflow occurred.
§Examples
assert_eq!(2u128.checked_pow(5), Some(32));
assert_eq!(0_u128.checked_pow(0), Some(1));
assert_eq!(u128::MAX.checked_pow(2), None);1.91.0 (const: 1.91.0) · Source
Strict exponentiation. Computes self.pow(exp), panicking if
overflow occurred.
§Panics
§Overflow behavior
This function will always panic on overflow, regardless of whether overflow checks are enabled.
§Examples
assert_eq!(2u128.strict_pow(5), 32);
assert_eq!(0_u128.strict_pow(0), 1);The following panics because of overflow:
let _ = u128::MAX.strict_pow(2);1.0.0 (const: 1.47.0) · Source
Saturating integer addition. Computes self + rhs, saturating at
the numeric bounds instead of overflowing.
§Examples
assert_eq!(100u128.saturating_add(1), 101);
assert_eq!(u128::MAX.saturating_add(127), u128::MAX);1.66.0 (const: 1.66.0) · Source
Saturating addition with a signed integer. Computes self + rhs,
saturating at the numeric bounds instead of overflowing.
§Examples
assert_eq!(1u128.saturating_add_signed(2), 3);
assert_eq!(1u128.saturating_add_signed(-2), 0);
assert_eq!((u128::MAX - 2).saturating_add_signed(4), u128::MAX);1.0.0 (const: 1.47.0) · Source
Saturating integer subtraction. Computes self - rhs, saturating
at the numeric bounds instead of overflowing.
§Examples
assert_eq!(100u128.saturating_sub(27), 73);
assert_eq!(13u128.saturating_sub(127), 0);1.90.0 (const: 1.90.0) · Source
Saturating integer subtraction. Computes self - rhs, saturating at
the numeric bounds instead of overflowing.
§Examples
assert_eq!(1u128.saturating_sub_signed(2), 0);
assert_eq!(1u128.saturating_sub_signed(-2), 3);
assert_eq!((u128::MAX - 2).saturating_sub_signed(-4), u128::MAX);1.7.0 (const: 1.47.0) · Source
Saturating integer multiplication. Computes self * rhs,
saturating at the numeric bounds instead of overflowing.
§Examples
assert_eq!(2u128.saturating_mul(10), 20);
assert_eq!((u128::MAX).saturating_mul(10), u128::MAX);1.58.0 (const: 1.58.0) · Source
1.34.0 (const: 1.50.0) · Source
Saturating integer exponentiation. Computes self.pow(exp),
saturating at the numeric bounds instead of overflowing.
§Examples
assert_eq!(4u128.saturating_pow(3), 64);
assert_eq!(0_u128.saturating_pow(0), 1);
assert_eq!(u128::MAX.saturating_pow(2), u128::MAX);1.0.0 (const: 1.32.0) · Source
Wrapping (modular) addition. Computes self + rhs,
wrapping around at the boundary of the type.
§Examples
assert_eq!(200u128.wrapping_add(55), 255);
assert_eq!(200u128.wrapping_add(u128::MAX), 199);1.66.0 (const: 1.66.0) · Source
Wrapping (modular) addition with a signed integer. Computes
self + rhs, wrapping around at the boundary of the type.
§Examples
assert_eq!(1u128.wrapping_add_signed(2), 3);
assert_eq!(1u128.wrapping_add_signed(-2), u128::MAX);
assert_eq!((u128::MAX - 2).wrapping_add_signed(4), 1);1.0.0 (const: 1.32.0) · Source
Wrapping (modular) subtraction. Computes self - rhs,
wrapping around at the boundary of the type.
§Examples
assert_eq!(100u128.wrapping_sub(100), 0);
assert_eq!(100u128.wrapping_sub(u128::MAX), 101);1.90.0 (const: 1.90.0) · Source
Wrapping (modular) subtraction with a signed integer. Computes
self - rhs, wrapping around at the boundary of the type.
§Examples
assert_eq!(1u128.wrapping_sub_signed(2), u128::MAX);
assert_eq!(1u128.wrapping_sub_signed(-2), 3);
assert_eq!((u128::MAX - 2).wrapping_sub_signed(-4), 1);1.0.0 (const: 1.32.0) · Source
Wrapping (modular) multiplication. Computes self * rhs, wrapping around at the boundary of the type.
§Examples
Please note that this example is shared among integer types, which is why u8 is used.
assert_eq!(10u8.wrapping_mul(12), 120);
assert_eq!(25u8.wrapping_mul(12), 44);1.2.0 (const: 1.52.0) · Source
Wrapping (modular) division. Computes self / rhs.
Wrapped division on unsigned types is just normal division. There’s no way wrapping could ever happen. This function exists so that all operations are accounted for in the wrapping operations.
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(100u128.wrapping_div(10), 10);1.38.0 (const: 1.52.0) · Source
Wrapping Euclidean division. Computes self.div_euclid(rhs).
Wrapped division on unsigned types is just normal division. There’s
no way wrapping could ever happen. This function exists so that all
operations are accounted for in the wrapping operations. Since, for
the positive integers, all common definitions of division are equal,
this is exactly equal to self.wrapping_div(rhs).
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(100u128.wrapping_div_euclid(10), 10);1.2.0 (const: 1.52.0) · Source
Wrapping (modular) remainder. Computes self % rhs.
Wrapped remainder calculation on unsigned types is just the regular remainder calculation. There’s no way wrapping could ever happen. This function exists so that all operations are accounted for in the wrapping operations.
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(100u128.wrapping_rem(10), 0);1.38.0 (const: 1.52.0) · Source
Wrapping Euclidean modulo. Computes self.rem_euclid(rhs).
Wrapped modulo calculation on unsigned types is just the regular
remainder calculation. There’s no way wrapping could ever happen.
This function exists so that all operations are accounted for in the
wrapping operations. Since, for the positive integers, all common
definitions of division are equal, this is exactly equal to
self.wrapping_rem(rhs).
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(100u128.wrapping_rem_euclid(10), 0);1.2.0 (const: 1.32.0) · Source
Wrapping (modular) negation. Computes -self,
wrapping around at the boundary of the type.
Since unsigned types do not have negative equivalents
all applications of this function will wrap (except for -0).
For values smaller than the corresponding signed type’s maximum
the result is the same as casting the corresponding signed value.
Any larger values are equivalent to MAX + 1 - (val - MAX - 1) where
MAX is the corresponding signed type’s maximum.
§Examples
assert_eq!(0_u128.wrapping_neg(), 0);
assert_eq!(u128::MAX.wrapping_neg(), 1);
assert_eq!(13_u128.wrapping_neg(), (!13) + 1);
assert_eq!(42_u128.wrapping_neg(), !(42 - 1));1.2.0 (const: 1.32.0) · Source
Panic-free bitwise shift-left; yields self << mask(rhs),
where mask removes any high-order bits of rhs that
would cause the shift to exceed the bitwidth of the type.
Note that this is not the same as a rotate-left; the
RHS of a wrapping shift-left is restricted to the range
of the type, rather than the bits shifted out of the LHS
being returned to the other end. The primitive integer
types all implement a rotate_left function,
which may be what you want instead.
§Examples
assert_eq!(1u128.wrapping_shl(7), 128);
assert_eq!(1u128.wrapping_shl(128), 1);1.2.0 (const: 1.32.0) · Source
Panic-free bitwise shift-right; yields self >> mask(rhs),
where mask removes any high-order bits of rhs that
would cause the shift to exceed the bitwidth of the type.
Note that this is not the same as a rotate-right; the
RHS of a wrapping shift-right is restricted to the range
of the type, rather than the bits shifted out of the LHS
being returned to the other end. The primitive integer
types all implement a rotate_right function,
which may be what you want instead.
§Examples
assert_eq!(128u128.wrapping_shr(7), 1);
assert_eq!(128u128.wrapping_shr(128), 128);1.34.0 (const: 1.50.0) · Source
Wrapping (modular) exponentiation. Computes self.pow(exp),
wrapping around at the boundary of the type.
§Examples
assert_eq!(3u128.wrapping_pow(5), 243);
assert_eq!(3u8.wrapping_pow(6), 217);
assert_eq!(0_u128.wrapping_pow(0), 1);1.7.0 (const: 1.32.0) · Source
Calculates self + rhs.
Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
§Examples
assert_eq!(5u128.overflowing_add(2), (7, false));
assert_eq!(u128::MAX.overflowing_add(1), (0, true));1.91.0 (const: unstable) · Source
Calculates self + rhs + carry and returns a tuple containing
the sum and the output carry (in that order).
Performs “ternary addition” of two integer operands and a carry-in bit, and returns an output integer and a carry-out bit. This allows chaining together multiple additions to create a wider addition, and can be useful for bignum addition.
This can be thought of as a 128-bit “full adder”, in the electronics sense.
If the input carry is false, this method is equivalent to
overflowing_add, and the output carry is
equal to the overflow flag. Note that although carry and overflow
flags are similar for unsigned integers, they are different for
signed integers.
§Examples
// 3 MAX (a = 3 × 2^128 + 2^128 - 1)
// + 5 7 (b = 5 × 2^128 + 7)
// ---------
// 9 6 (sum = 9 × 2^128 + 6)
let (a1, a0): (u128, u128) = (3, u128::MAX);
let (b1, b0): (u128, u128) = (5, 7);
let carry0 = false;
let (sum0, carry1) = a0.carrying_add(b0, carry0);
assert_eq!(carry1, true);
let (sum1, carry2) = a1.carrying_add(b1, carry1);
assert_eq!(carry2, false);
assert_eq!((sum1, sum0), (9, 6));1.66.0 (const: 1.66.0) · Source
Calculates self + rhs with a signed rhs.
Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
§Examples
assert_eq!(1u128.overflowing_add_signed(2), (3, false));
assert_eq!(1u128.overflowing_add_signed(-2), (u128::MAX, true));
assert_eq!((u128::MAX - 2).overflowing_add_signed(4), (1, true));1.7.0 (const: 1.32.0) · Source
Calculates self - rhs.
Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
§Examples
assert_eq!(5u128.overflowing_sub(2), (3, false));
assert_eq!(0u128.overflowing_sub(1), (u128::MAX, true));1.91.0 (const: unstable) · Source
Calculates self − rhs − borrow and returns a tuple
containing the difference and the output borrow.
Performs “ternary subtraction” by subtracting both an integer
operand and a borrow-in bit from self, and returns an output
integer and a borrow-out bit. This allows chaining together multiple
subtractions to create a wider subtraction, and can be useful for
bignum subtraction.
§Examples
// 9 6 (a = 9 × 2^128 + 6)
// - 5 7 (b = 5 × 2^128 + 7)
// ---------
// 3 MAX (diff = 3 × 2^128 + 2^128 - 1)
let (a1, a0): (u128, u128) = (9, 6);
let (b1, b0): (u128, u128) = (5, 7);
let borrow0 = false;
let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
assert_eq!(borrow1, true);
let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
assert_eq!(borrow2, false);
assert_eq!((diff1, diff0), (3, u128::MAX));1.90.0 (const: 1.90.0) · Source
Calculates self - rhs with a signed rhs
Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
§Examples
assert_eq!(1u128.overflowing_sub_signed(2), (u128::MAX, true));
assert_eq!(1u128.overflowing_sub_signed(-2), (3, false));
assert_eq!((u128::MAX - 2).overflowing_sub_signed(-4), (1, true));1.60.0 (const: 1.60.0) · Source
Computes the absolute difference between self and other.
§Examples
assert_eq!(100u128.abs_diff(80), 20u128);
assert_eq!(100u128.abs_diff(110), 10u128);1.7.0 (const: 1.32.0) · Source
Calculates the multiplication of self and rhs.
Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned.
If you want the value of the overflow, rather than just whether
an overflow occurred, see Self::carrying_mul.
§Examples
Please note that this example is shared among integer types, which is why u32 is used.
assert_eq!(5u32.overflowing_mul(2), (10, false));
assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));Source 🔬This is a nightly-only experimental API. (bigint_helper_methods #85532)
bigint_helper_methods #85532)Calculates the complete double-width product self * rhs.
This returns the low-order (wrapping) bits and the high-order (overflow) bits
of the result as two separate values, in that order. As such,
a.widening_mul(b).0 produces the same result as a.wrapping_mul(b).
If you also need to add a value and carry to the wide result, then you want
Self::carrying_mul_add instead.
If you also need to add a carry to the wide result, then you want
Self::carrying_mul instead.
If you just want to know whether the multiplication overflowed, then you
want Self::overflowing_mul instead.
§Examples
#![feature(bigint_helper_methods)]
assert_eq!(5_u128.widening_mul(7), (35, 0));
assert_eq!(u128::MAX.widening_mul(u128::MAX), (1, u128::MAX - 1));Compared to other *_mul methods:
#![feature(bigint_helper_methods)]
assert_eq!(u128::widening_mul(1 << 127, 6), (0, 3));
assert_eq!(u128::overflowing_mul(1 << 127, 6), (0, true));
assert_eq!(u128::wrapping_mul(1 << 127, 6), 0);
assert_eq!(u128::checked_mul(1 << 127, 6), None);Please note that this example is shared among integer types, which is why u32 is used.
#![feature(bigint_helper_methods)]
assert_eq!(5u32.widening_mul(2), (10, 0));
assert_eq!(1_000_000_000u32.widening_mul(10), (1410065408, 2));1.91.0 (const: unstable) · Source
Calculates the “full multiplication” self * rhs + carry
without the possibility to overflow.
This returns the low-order (wrapping) bits and the high-order (overflow) bits of the result as two separate values, in that order.
Performs “long multiplication” which takes in an extra amount to add, and may return an additional amount of overflow. This allows for chaining together multiple multiplications to create “big integers” which represent larger values.
If you also need to add a value, then use Self::carrying_mul_add.
§Examples
Please note that this example is shared among integer types, which is why u32 is used.
assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
assert_eq!(u128::MAX.carrying_mul(u128::MAX, u128::MAX), (0, u128::MAX));This is the core operation needed for scalar multiplication when implementing it for wider-than-native types.
#![feature(bigint_helper_methods)]
fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
let mut carry = 0;
for d in little_endian_digits.iter_mut() {
(*d, carry) = d.carrying_mul(multiplicand, carry);
}
if carry != 0 {
little_endian_digits.push(carry);
}
}
let mut v = vec![10, 20];
scalar_mul_eq(&mut v, 3);
assert_eq!(v, [30, 60]);
assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
let mut v = vec![0x4321, 0x8765];
scalar_mul_eq(&mut v, 0xFEED);
assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);If carry is zero, this is similar to overflowing_mul,
except that it gives the value of the overflow instead of just whether one happened:
#![feature(bigint_helper_methods)]
let r = u8::carrying_mul(7, 13, 0);
assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
let r = u8::carrying_mul(13, 42, 0);
assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));The value of the first field in the returned tuple matches what you’d get
by combining the wrapping_mul and
wrapping_add methods:
#![feature(bigint_helper_methods)]
assert_eq!(
789_u16.carrying_mul(456, 123).0,
789_u16.wrapping_mul(456).wrapping_add(123),
);1.91.0 (const: unstable) · Source
Calculates the “full multiplication” self * rhs + carry + add.
This returns the low-order (wrapping) bits and the high-order (overflow) bits of the result as two separate values, in that order.
This cannot overflow, as the double-width result has exactly enough space for the largest possible result. This is equivalent to how, in decimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
Performs “long multiplication” which takes in an extra amount to add, and may return an additional amount of overflow. This allows for chaining together multiple multiplications to create “big integers” which represent larger values.
If you don’t need the add part, then you can use Self::carrying_mul instead.
§Examples
Please note that this example is shared between integer types,
which explains why u32 is used here.
assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
assert_eq!(u128::MAX.carrying_mul_add(u128::MAX, u128::MAX, u128::MAX), (u128::MAX, u128::MAX));This is the core per-digit operation for “grade school” O(n²) multiplication.
Please note that this example is shared between integer types,
using u8 for simplicity of the demonstration.
fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
let mut out = [0; N];
for j in 0..N {
let mut carry = 0;
for i in 0..(N - j) {
(out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
}
}
out
}
// -1 * -1 == 1
assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);
assert_eq!(
quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
u32::to_le_bytes(0xcffc982d)
);1.7.0 (const: 1.52.0) · Source
Calculates the divisor when self is divided by rhs.
Returns a tuple of the divisor along with a boolean indicating
whether an arithmetic overflow would occur. Note that for unsigned
integers overflow never occurs, so the second value is always
false.
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(5u128.overflowing_div(2), (2, false));1.38.0 (const: 1.52.0) · Source
Calculates the quotient of Euclidean division self.div_euclid(rhs).
Returns a tuple of the divisor along with a boolean indicating
whether an arithmetic overflow would occur. Note that for unsigned
integers overflow never occurs, so the second value is always
false.
Since, for the positive integers, all common
definitions of division are equal, this
is exactly equal to self.overflowing_div(rhs).
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(5u128.overflowing_div_euclid(2), (2, false));1.7.0 (const: 1.52.0) · Source
Calculates the remainder when self is divided by rhs.
Returns a tuple of the remainder after dividing along with a boolean
indicating whether an arithmetic overflow would occur. Note that for
unsigned integers overflow never occurs, so the second value is
always false.
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(5u128.overflowing_rem(2), (1, false));1.38.0 (const: 1.52.0) · Source
Calculates the remainder self.rem_euclid(rhs) as if by Euclidean division.
Returns a tuple of the modulo after dividing along with a boolean
indicating whether an arithmetic overflow would occur. Note that for
unsigned integers overflow never occurs, so the second value is
always false.
Since, for the positive integers, all common
definitions of division are equal, this operation
is exactly equal to self.overflowing_rem(rhs).
§Panics
This function will panic if rhs is zero.
§Examples
assert_eq!(5u128.overflowing_rem_euclid(2), (1, false));1.7.0 (const: 1.32.0) · Source
Negates self in an overflowing fashion.
Returns !self + 1 using wrapping operations to return the value
that represents the negation of this unsigned value. Note that for
positive unsigned values overflow always occurs, but negating 0 does
not overflow.
§Examples
assert_eq!(0u128.overflowing_neg(), (0, false));
assert_eq!(2u128.overflowing_neg(), (-2i32 as u128, true));1.7.0 (const: 1.32.0) · Source
Shifts self left by rhs bits.
Returns a tuple of the shifted version of self along with a boolean indicating whether the shift value was larger than or equal to the number of bits. If the shift value is too large, then value is masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
§Examples
assert_eq!(0x1u128.overflowing_shl(4), (0x10, false));
assert_eq!(0x1u128.overflowing_shl(132), (0x10, true));
assert_eq!(0x10u128.overflowing_shl(127), (0, false));1.7.0 (const: 1.32.0) · Source
Shifts self right by rhs bits.
Returns a tuple of the shifted version of self along with a boolean indicating whether the shift value was larger than or equal to the number of bits. If the shift value is too large, then value is masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
§Examples
assert_eq!(0x10u128.overflowing_shr(4), (0x1, false));
assert_eq!(0x10u128.overflowing_shr(132), (0x1, true));1.34.0 (const: 1.50.0) · Source
Raises self to the power of exp, using exponentiation by squaring.
Returns a tuple of the exponentiation along with a bool indicating whether an overflow happened.
§Examples
assert_eq!(3u128.overflowing_pow(5), (243, false));
assert_eq!(0_u128.overflowing_pow(0), (1, false));
assert_eq!(3u8.overflowing_pow(6), (217, true));1.0.0 (const: 1.50.0) · Source
Raises self to the power of exp, using exponentiation by squaring.
§Examples
assert_eq!(2u128.pow(5), 32);
assert_eq!(0_u128.pow(0), 1);1.84.0 (const: 1.84.0) · Source
1.38.0 (const: 1.52.0) · Source
1.38.0 (const: 1.52.0) · Source
1.73.0 (const: 1.73.0) · Source
1.73.0 (const: 1.73.0) · Source
Calculates the smallest value greater than or equal to self that
is a multiple of rhs.
§Panics
This function will panic if rhs is zero.
§Overflow behavior
On overflow, this function will panic if overflow checks are enabled (default in debug mode) and wrap if overflow checks are disabled (default in release mode).
§Examples
assert_eq!(16_u128.next_multiple_of(8), 16);
assert_eq!(23_u128.next_multiple_of(8), 24);1.73.0 (const: 1.73.0) · Source
Calculates the smallest value greater than or equal to self that
is a multiple of rhs. Returns None if rhs is zero or the
operation would result in overflow.
§Examples
assert_eq!(16_u128.checked_next_multiple_of(8), Some(16));
assert_eq!(23_u128.checked_next_multiple_of(8), Some(24));
assert_eq!(1_u128.checked_next_multiple_of(0), None);
assert_eq!(u128::MAX.checked_next_multiple_of(2), None);1.87.0 (const: 1.87.0) · Source
Returns true if self is an integer multiple of rhs, and false otherwise.
This function is equivalent to self % rhs == 0, except that it will not panic
for rhs == 0. Instead, 0.is_multiple_of(0) == true, and for any non-zero n,
n.is_multiple_of(0) == false.
§Examples
assert!(6_u128.is_multiple_of(2));
assert!(!5_u128.is_multiple_of(2));
assert!(0_u128.is_multiple_of(0));
assert!(!6_u128.is_multiple_of(0));1.0.0 (const: 1.32.0) · Source
Returns true if and only if self == 2^k for some unsigned integer k.
§Examples
assert!(16u128.is_power_of_two());
assert!(!10u128.is_power_of_two());1.0.0 (const: 1.50.0) · Source
Returns the smallest power of two greater than or equal to self.
When return value overflows (i.e., self > (1 << (N-1)) for type
uN), it panics in debug mode and the return value is wrapped to 0 in
release mode (the only situation in which this method can return 0).
§Examples
assert_eq!(2u128.next_power_of_two(), 2);
assert_eq!(3u128.next_power_of_two(), 4);
assert_eq!(0u128.next_power_of_two(), 1);1.0.0 (const: 1.50.0) · Source
Returns the smallest power of two greater than or equal to self. If
the next power of two is greater than the type’s maximum value,
None is returned, otherwise the power of two is wrapped in Some.
§Examples
assert_eq!(2u128.checked_next_power_of_two(), Some(2));
assert_eq!(3u128.checked_next_power_of_two(), Some(4));
assert_eq!(u128::MAX.checked_next_power_of_two(), None);Source 🔬This is a nightly-only experimental API. (wrapping_next_power_of_two #32463)
wrapping_next_power_of_two #32463)Returns the smallest power of two greater than or equal to n. If
the next power of two is greater than the type’s maximum value,
the return value is wrapped to 0.
§Examples
#![feature(wrapping_next_power_of_two)]
assert_eq!(2u128.wrapping_next_power_of_two(), 2);
assert_eq!(3u128.wrapping_next_power_of_two(), 4);
assert_eq!(u128::MAX.wrapping_next_power_of_two(), 0);1.32.0 (const: 1.44.0) · Source
Returns the memory representation of this integer as a byte array in big-endian (network) byte order.
§Examples
let bytes = 0x12345678901234567890123456789012u128.to_be_bytes();
assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);1.32.0 (const: 1.44.0) · Source
Returns the memory representation of this integer as a byte array in little-endian byte order.
§Examples
let bytes = 0x12345678901234567890123456789012u128.to_le_bytes();
assert_eq!(bytes, [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);1.32.0 (const: 1.44.0) · Source
Returns the memory representation of this integer as a byte array in native byte order.
As the target platform’s native endianness is used, portable code
should use to_be_bytes or to_le_bytes, as appropriate,
instead.
§Examples
let bytes = 0x12345678901234567890123456789012u128.to_ne_bytes();
assert_eq!(
bytes,
if cfg!(target_endian = "big") {
[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]
} else {
[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]
}
);1.32.0 (const: 1.44.0) · Source
Creates a native endian integer value from its representation as a byte array in big endian.
§Examples
let value = u128::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);
assert_eq!(value, 0x12345678901234567890123456789012);When starting from a slice rather than an array, fallible conversion APIs can be used:
fn read_be_u128(input: &mut &[u8]) -> u128 {
let (int_bytes, rest) = input.split_at(size_of::<u128>());
*input = rest;
u128::from_be_bytes(int_bytes.try_into().unwrap())
}1.32.0 (const: 1.44.0) · Source
Creates a native endian integer value from its representation as a byte array in little endian.
§Examples
let value = u128::from_le_bytes([0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);
assert_eq!(value, 0x12345678901234567890123456789012);When starting from a slice rather than an array, fallible conversion APIs can be used:
fn read_le_u128(input: &mut &[u8]) -> u128 {
let (int_bytes, rest) = input.split_at(size_of::<u128>());
*input = rest;
u128::from_le_bytes(int_bytes.try_into().unwrap())
}1.32.0 (const: 1.44.0) · Source
Creates a native endian integer value from its memory representation as a byte array in native endianness.
As the target platform’s native endianness is used, portable code
likely wants to use from_be_bytes or from_le_bytes, as
appropriate instead.
§Examples
let value = u128::from_ne_bytes(if cfg!(target_endian = "big") {
[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]
} else {
[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]
});
assert_eq!(value, 0x12345678901234567890123456789012);When starting from a slice rather than an array, fallible conversion APIs can be used:
fn read_ne_u128(input: &mut &[u8]) -> u128 {
let (int_bytes, rest) = input.split_at(size_of::<u128>());
*input = rest;
u128::from_ne_bytes(int_bytes.try_into().unwrap())
}1.0.0 (const: 1.32.0) · Source 👎Deprecating in a future version: replaced by the MIN associated constant on this type
MIN associated constant on this typeNew code should prefer to use
u128::MIN instead.
Returns the smallest value that can be represented by this integer type.
1.0.0 (const: 1.32.0) · Source 👎Deprecating in a future version: replaced by the MAX associated constant on this type
MAX associated constant on this typeNew code should prefer to use
u128::MAX instead.
Returns the largest value that can be represented by this integer type.
1.85.0 (const: 1.85.0) · Source
Calculates the midpoint (average) between self and rhs.
midpoint(a, b) is (a + b) / 2 as if it were performed in a
sufficiently-large unsigned integral type. This implies that the result is
always rounded towards zero and that no overflow will ever occur.
§Examples
assert_eq!(0u128.midpoint(4), 2);
assert_eq!(1u128.midpoint(4), 2);Source§
1.0.0 (const: 1.82.0) · Source
Parses an integer from a string slice with digits in a given base.
The string is expected to be an optional
+
sign followed by only digits. Leading and trailing non-digit characters (including
whitespace) represent an error. Underscores (which are accepted in Rust literals)
also represent an error.
Digits are a subset of these characters, depending on radix:
0-9a-zA-Z
§Panics
This function panics if radix is not in the range from 2 to 36.
§See also
If the string to be parsed is in base 10 (decimal),
from_str or str::parse can also be used.
§Examples
assert_eq!(u128::from_str_radix("A", 16), Ok(10));Trailing space returns error:
assert!(u128::from_str_radix("1 ", 10).is_err());Source 🔬This is a nightly-only experimental API. (int_from_ascii #134821)
int_from_ascii #134821)Parses an integer from an ASCII-byte slice with decimal digits.
The characters are expected to be an optional
+
sign followed by only digits. Leading and trailing non-digit characters (including
whitespace) represent an error. Underscores (which are accepted in Rust literals)
also represent an error.
§Examples
#![feature(int_from_ascii)]
assert_eq!(u128::from_ascii(b"+10"), Ok(10));Trailing space returns error:
assert!(u128::from_ascii(b"1 ").is_err());Source 🔬This is a nightly-only experimental API. (int_from_ascii #134821)
int_from_ascii #134821)Parses an integer from an ASCII-byte slice with digits in a given base.
The characters are expected to be an optional
+
sign followed by only digits. Leading and trailing non-digit characters (including
whitespace) represent an error. Underscores (which are accepted in Rust literals)
also represent an error.
Digits are a subset of these characters, depending on radix:
0-9a-zA-Z
§Panics
This function panics if radix is not in the range from 2 to 36.
§Examples
#![feature(int_from_ascii)]
assert_eq!(u128::from_ascii_radix(b"A", 16), Ok(10));Trailing space returns error:
assert!(u128::from_ascii_radix(b"1 ", 10).is_err());Source§
Source 🔬This is a nightly-only experimental API. (int_format_into #138215)
int_format_into #138215)Allows users to write an integer (in signed decimal format) into a variable buf of
type NumBuffer that is passed by the caller by mutable reference.
§Examples
#![feature(int_format_into)]
use core::fmt::NumBuffer;
let n = 0u128;
let mut buf = NumBuffer::new();
assert_eq!(n.format_into(&mut buf), "0");
let n1 = 32u128;
let mut buf1 = NumBuffer::new();
assert_eq!(n1.format_into(&mut buf1), "32");
let n2 = u128::MAX;
let mut buf2 = NumBuffer::new();
assert_eq!(n2.format_into(&mut buf2), u128::MAX.to_string());Source§
Source§
🔬This is a nightly-only experimental API. (core_intrinsics_fallbacks)
See super::disjoint_bitor; we just need the trait indirection to handle
different types since calling intrinsics with generics doesn’t work.
1.0.0 (const: unstable) · Source§This operation rounds towards zero, truncating any
fractional part of the exact result.
This operation rounds towards zero, truncating any fractional part of the exact result.
§Panics
This operation will panic if other == 0.
1.0.0 (const: unstable) · Source§
Source§
Parses an integer from a string slice with decimal digits.
The characters are expected to be an optional
+
sign followed by only digits. Leading and trailing non-digit characters (including
whitespace) represent an error. Underscores (which are accepted in Rust literals)
also represent an error.
§See also
For parsing numbers in other bases, such as binary or hexadecimal,
see from_str_radix.
§Examples
use std::str::FromStr;
assert_eq!(u128::from_str("+10"), Ok(10));Trailing space returns error:
assert!(u128::from_str("1 ").is_err());Source§
Source§
🔬This is a nightly-only experimental API. (core_intrinsics_fallbacks)
See super::unchecked_funnel_shl; we just need the trait indirection to handle
different types since calling intrinsics with generics doesn’t work.
Source§
🔬This is a nightly-only experimental API. (core_intrinsics_fallbacks)
See super::unchecked_funnel_shr; we just need the trait indirection to handle
different types since calling intrinsics with generics doesn’t work.
Source§
1.0.0 (const: unstable) · Source§This operation satisfies n % d == n - (n / d) * d. The
result has the same sign as the left operand.
This operation satisfies n % d == n - (n / d) * d. The
result has the same sign as the left operand.
§Panics
This operation will panic if other == 0.
Source§
Source§
🔬This is a nightly-only experimental API. (step_trait #42168)
Returns the value that would be obtained by taking the successor
of self count times. Read more
Source§
🔬This is a nightly-only experimental API. (step_trait #42168)
Returns the value that would be obtained by taking the predecessor
of self count times. Read more
Source§
🔬This is a nightly-only experimental API. (step_trait #42168)
Returns the value that would be obtained by taking the successor
of self count times. Read more
Source§
🔬This is a nightly-only experimental API. (step_trait #42168)
Returns the value that would be obtained by taking the predecessor
of self count times. Read more
Source§
🔬This is a nightly-only experimental API. (step_trait #42168)
Returns the bounds on the number of successor steps required to get from start to end
like Iterator::size_hint(). Read more