[SOLVED] How to convert big hex strings to decimal strings?


This Content is from Stack Overflow. Question asked by TIZ

I am working with big numbers in rust, my inputs come in as hex strings and I am using a hash function which has done all the heavy lifting with large numbers, all I need to do is to provide it with decimal string versions of the numbers (not hex). What would be the best practice to convert hex strings to their equivalent decimal representation, whilst staying within strings in order not to cause any overflow issues.


I don’t think implementing this by hand is a trivial problem. It will involve a lot of error-prone math on strings and it will be quite slow in the end. String based math in general is quite slow.

There are excellent big integer libraries out there, though. For example num:

use num::{BigInt, Num};

fn convert_hex_to_dec(hex_str: &str) -> String {
    BigInt::from_str_radix(hex_str, 16).unwrap().to_string()

fn main() {
    let hex_str = "978d54b635d7a829d5e3d9bee5a56018ba5e01c10";
    let dec_str = convert_hex_to_dec(hex_str);
    println!("{}", dec_str);

If you planned to do your entire math with strings, I’d advice using BigInts instead.

This Question was asked in StackOverflow by TIZ and Answered by Finomnis It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?