解析csv文件中的50位整数:ParseIntError {kind:Overflow}

时间:2019-06-15 07:45:04

标签: rust rust-crates

可以解析为u128的最大位数是多少。我在尝试解析50位正整数时遇到Err(ParseIntError { kind: Overflow })

我的错误:

...
...
result: id 89 "40789923115535562561142322423255033685442488917353"      Err(ParseIntError { kind: Overflow })
result: id 90 "44889911501440648020369068063960672322193204149535"      Err(ParseIntError { kind: Overflow })
result: id 91 "41503128880339536053299340368006977710650566631954"      Err(ParseIntError { kind: Overflow })
result: id 92 "81234880673210146739058568557934581403627822703280"      Err(ParseIntError { kind: Overflow })
result: id 93 "82616570773948327592232845941706525094512325230608"      Err(ParseIntError { kind: Overflow })
result: id 94 "22918802058777319719839450180888072429661980811197"      Err(ParseIntError { kind: Overflow })
result: id 95 "77158542502016545090413245809786882778948721859617"      Err(ParseIntError { kind: Overflow })
result: id 96 "72107838435069186155435662884062257473692284509516"      Err(ParseIntError { kind: Overflow })
result: id 97 "20849603980134001723930671666823555245252804609722"      Err(ParseIntError { kind: Overflow })
result: id 98 "53503534226472524250874054075591789781264330331690"      Err(ParseIntError { kind: Overflow })
...
...

与此对应的代码:

fn read_num(a: &mut Reader<File>) -> Result<u128, Error> {
    let mut sum: u128 = 0;
    for(idx, res) in a.records().enumerate() {
        let res = res.unwrap();
        let val: StringRecord = res;
        let ii = val.get(0).unwrap().trim().parse::<u128>().unwrpa();
        println!("result: id {} {:?}\t {:?}", idx, val.get(0).unwrap(), ii);
    }; // This is formatted
    Ok(sum)
}

我最初认为它必须是每行末尾的换行符,但是trim应该删除它,并且在我看来它正在删除,因为未解析的输出似乎没有\t

中除了println!格式化程序外,什么都没有

溢出是由于固有的限制还是我做错了什么?

1 个答案:

答案 0 :(得分:2)

最大的u128是2 ** 128-1 = 340282366920938463463374374607431768211455,该数字少于50位,因此您将必须使用struct num::bigint::BigInt(来自num板条箱)。 / p>

您可以通过FromStr特征来解析大整数。这是解析两个50位数字并乘以(超级奖励时间)的示例:

extern crate num;

use num::BigInt;
use std::str::FromStr;
use std::ops::Mul;

fn main() {
    let x = BigInt::from_str("9879878782352398572398755757923351299981243778899").unwrap();
    let y = BigInt::from_str("3234235766473868388883432903721391827312463782828").unwrap();
    println!("{}", x.mul(y));
}