I want the following
(2u128.pow(x)) as u64
but such that it succeeds for x < 64 and fails for x >= 64.
As you correctly pointed out yourself, you should use TryFrom, but you should also make sure the exponentiation itself doesn't overflow, by using u128::checked_pow instead of u128::pow:
use std::convert::TryFrom;
let x = 129;
let y = 2u128.checked_pow(x).expect("Number too big for exponentiation");
let z = u64::try_from(y).expect("Number too big for cast");
(playground link)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With