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?
CodePudding user response:
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);
}
13843350254437927549667668733810160916738275810320
If you planned to do your entire math with strings, I'd advice using BigInt
s instead.