我需要一个随机的256位无符号数字。我发现RandBigInt该方法gen_biguint()具有特性,但是我很难找到实现它的方法。
我试过一段时间才这样做BigInt。此后,箱子已更新。这就是我用它来获得BigUint现在的方式。
extern crate num;
extern crate rand;
use num::bigint::{BigInt, BigUint, RandBigInt};
fn main() {
let mut rng = rand::thread_rng();
let mut n: BigUint = BigUint::default();
loop {
let bigUint: Option<BigUint> = rng.gen_bigint(256).to_biguint();
match bigUint {
Some(num) => {
n = num.clone();
println!("Found the 1st BigUint - {}", num);
break;
}
_ => {}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的Cargo.toml中的内容
extern crate num;
extern crate rand;
use num::bigint::{BigInt, BigUint, RandBigInt};
fn main() {
let mut rng = rand::thread_rng();
let mut n: BigUint = BigUint::default();
loop {
let bigUint: Option<BigUint> = rng.gen_bigint(256).to_biguint();
match bigUint {
Some(num) => {
n = num.clone();
println!("Found the 1st BigUint - {}", num);
break;
}
_ => {}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我确信必须有一些简单的方法来实现这一目标。
从的自述文件num:
该
rand功能允许在随机的特征num-bigint和num-complex。
[dependencies]
num-bigint = { version = "0.2.0", features = ["rand"] }
rand = "0.5.4"
Run Code Online (Sandbox Code Playgroud)
然后,您需要使用RandomBits实现的rand::Distribution:
extern crate num_bigint;
extern crate rand;
use num_bigint::{BigInt, BigUint, RandomBits};
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let signed: BigInt = rng.sample(RandomBits::new(256));
let unsigned: BigUint = rng.sample(RandomBits::new(256));
println!("{}, {}", signed, unsigned)
}
Run Code Online (Sandbox Code Playgroud)