1

I want to convert 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i base58 string into hexadecimal string. I began to do it from converting base58 into decimal number and after that into heximal string.

fn base58_decode(code: &String) -> u128 {
  use std::collections::HashMap;

  const ALPHABET: &str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

  let keys = ALPHABET.chars();
  let map: HashMap<_, u128> = keys.zip(0..).collect();

  let mut result: u128 = 0;

  for (n, ch) in code.chars().rev().enumerate() {
    let value = map.get(&ch);
    result += value.unwrap() * 58u128.pow(n as u32);
  }

  result
}

But this code throw overflow panic, so I need better algorithm for it.

ChzChz
  • 57
  • 3
  • 2
    You can't convert the given base58 string into a `u128` because it contains almost 200 (`34*log2(58)`) bits of information, while `u128` can only hold 128 bits. I'd recommend you consider one of the existing crates for this, e.g. [`bs58`](https://docs.rs/bs58/*/bs58/), [`base58`](https://docs.rs/base58/*/base58/) or [`rust-base58`](https://docs.rs/rust-base58/*/rust_base58/), to convert into a byte array, and then [`hex`](https://docs.rs/hex/*/hex/) to convert it into hexadecimal. – Frxstrem Apr 12 '20 at 18:09
  • @Frxstrem Yes, I know about libs for decoding and encoding base58, but I would like to understand the algorithm for it. But I'm too bad in rust so it isn't clear for me from source. – ChzChz Apr 13 '20 at 09:34

0 Answers0