代码之家  ›  专栏  ›  技术社区  ›  AurevoirXavier

如何将非常大的十进制字符串转换为十六进制?

  •  1
  • AurevoirXavier  · 技术社区  · 7 年前
    let hex = "100000000000000000".as_bytes().to_hex();
    // hex == "313030303030303030303030303030303030"
    
    println!("{:x}", 100000000000000000000000u64);
    // literal out of range for u64
    

    我怎样才能得到那个值?

    hex(100000000000000000000000) 我得到 '0x152d02c7e14af6800000' .

    to_hex() hex crate .

    1 回复  |  直到 7 年前
        1
  •  3
  •   Shepmaster Tim Diekmann    7 年前

    我们需要了解Rust中不同数字类型的可表示值的范围。在这种特殊情况下,该值超过了 u64 u128 类型容纳该值。以下代码输出的值与Python中的示例相同:

    fn main() {
        let my_string = "100000000000000000000000".to_string();  // `parse()` works with `&str` and `String`!
        let my_int = my_string.parse::<u128>().unwrap();
        let my_hex = format!("{:X}", my_int);
        println!("{}", my_hex);
    }
    

    经检查 Rust Playground

    152D02C7E14AF6800000
    

    在一般情况下,需要明确使用任意精度的算法。来自中国的几点建议 What's the best crate for arbitrary precision arithmetic in Rust?

    • num_bigint 在稳定的环境下工作,没有不安全的代码。
    • ramp 使用不安全且不适用于稳定锈蚀,但速度更快。
    • rust-gmp rug 绑定到C(GMP)中最先进的bigint实现。它们速度最快,功能最多。你可能想用其中一个。
    推荐文章