Home > Enterprise >  Is there a way to do a right bit-shift on a BigInt in Rust?
Is there a way to do a right bit-shift on a BigInt in Rust?

Time:01-06

I get this error when attempting to do >> or >>= on a BigInt:

no implementation for `BigInt >> BigInt

using the num_bigint::BigInt library

Edit: More Context:

I am rewriting this program https://www.geeksforgeeks.org/how-to-generate-large-prime-numbers-for-rsa-algorithm/ from python/c into rust however I will focus on the python implementation as it is written to handle 1024 bit prime numbers which are extremely big.

In the code we run the Miller Rabin Primality test which includes shifting EC: (prime-candidate - 1) to the right by 1 if we find that EC % 2 == 0. As I mentioned in the python implementation EC can be an incredibly large integer.

It would be convenient to be able to use the same operator in rust, if that is not possible can someone suggest an alternative?

CodePudding user response:

According to the documentation for the num-bigint crate, the BigInt struct does implement the Shr trait for the right-shift operator, just not when the shift amount is itself a BigInt. If you convert the shift amount to a standard integer type (e.g. i64) then it should work.

It is unlikely you would ever want to shift by an amount greater than i64::MAX, but if you do need this, then the correct result is going to be zero (because no computer has 2^60 bytes of memory), so you can write a simple implementation which checks for that case.

  • Related