PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

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

 October 24, 2022     decimal, hex, rust, string     No comments   

Issue

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?


Solution

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 BigInts instead.



Answered By - Finomnis
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing