In most cases, you want to parse more than one hex byte at once. In those cases, use the hex crate.

parse this into an integer

You want to use from_str_radix. It's implemented on the integer types.

use std::i64;

fn main() {
    let z = i64::from_str_radix("1f", 16);
    println!("{:?}", z);
}

If your strings actually have the 0x prefix, then you will need to skip over them. The best way to do that is via trim_start_matches or strip_prefix:

use std::i64;

fn main() {
    let raw = "0x1f";
    let without_prefix = raw.trim_start_matches("0x");
    let z = i64::from_str_radix(without_prefix, 16);
    println!("{:?}", z);
}
Answer from Shepmaster on Stack Overflow
🌐
W3Resource
w3resource.com › rust › error_handling › rust-result-and-option-types-exercise-7.php
Rust Function: Hex string to integer
June 10, 2025 - fn hex_string_to_int(hex_string: &str) -> Option<u64> { // Attempt to parse the hexadecimal string into a u64 integer match u64::from_str_radix(hex_string, 16) { // If parsing succeeds, return the parsed integer wrapped in Some Ok(parsed_int) ...
Discussions

Converting &str that contains a decimal or hex representation to a decimal in a generic way
I was trying to write a generic function that could take a &str containing either a decimal representation 123, or a hexadecimal representation 0xFF and parse this into a decimal number. use num_traits::Num; fn parse … More on users.rust-lang.org
🌐 users.rust-lang.org
6
0
December 14, 2020
How to easily translate hex string into usize or bytes
for example, I'm gotting "0x2A2F" and how to translate it into the actual number? I want a high performance way without other crates. Or if there is a good crate implemented for it, I'm going to learn about it. More on users.rust-lang.org
🌐 users.rust-lang.org
2
0
January 3, 2024
Convert hex string to integer in Python - Stack Overflow
How do I convert a hex string to an integer? "0xffff" ⟶ 65535 "ffff" ⟶ 65535 More on stackoverflow.com
🌐 stackoverflow.com
beginner - Converting a hexadecimal string to a binary string using Rust pattern matching lookup - Code Review Stack Exchange
I am getting started in Rust, and as a part of my first exercise, I decided to write a small program that converts a hexadecimal string to a binary string using a pattern matched lookup. I would More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
September 11, 2019
🌐
Programming Idioms
programming-idioms.org › idiom › 142 › hexadecimal-digits-of-an-integer › 2346 › rust
Hexadecimal digits of an integer, in Rust
Python · Ruby · Rust · Or search : Assign to string s the hexadecimal representation (base 16) of integer x. E.g. 999 -> "3e7" Hexadecimal in Wikipedia · Rust · C · Clojure · C++ C++ C++ C# D · D · Dart · Elixir · Erlang · Fortran · Go · Go · Haskell ·
🌐
mkaz.blog
mkaz.blog › working-with-rust › numbers
Numbers - mkaz.blog
Or when converting string to float, specify the float type inline to the parse function, using ::<> syntax: let str = "2.71828"; let e = str.parse::<f32>().unwrap(); To convert a single char to an integer in Rust, use .to_digit(RADIX). The radix value is used for conversion, 10 for decimal, ...
🌐
Rust Programming Language
users.rust-lang.org › help
Converting &str that contains a decimal or hex representation to a decimal in a generic way - help - The Rust Programming Language Forum
December 14, 2020 - I was trying to write a generic function that could take a &str containing either a decimal representation 123, or a hexadecimal representation 0xFF and parse this into a decimal number. use num_traits::Num; fn parse …
🌐
Rust Programming Language
users.rust-lang.org › help
How to easily translate hex string into usize or bytes - help - The Rust Programming Language Forum
January 3, 2024 - for example, I'm gotting "0x2A2F" and how to translate it into the actual number? I want a high performance way without other crates. Or if there is a good crate implemented for it, I'm going to learn about it.
Find elsewhere
Top answer
1 of 1
2
  • Rustfmt is a tool for automatically formatting Rust code to the community-accepted style.
  • Clippy is a tool for finding common mistakes that may not be compilation errors but are unlikely to be what the programmer intended.

Rustfmt points out that you are using 3-space indents (Rust uses 4), and that some of your lines don't need to be split.

Clippy points out:

warning: returning the result of a let binding from a block
 --> src/main.rs:9:5
  |
7 |     let to_binary = hex[2..].chars().map(|c| to_binary(c)).collect();
  |     ----------------------------------------------------------------- unnecessary let binding
8 |
9 |     to_binary
  |     ^^^^^^^^^
  |
  = note: #[warn(clippy::let_and_return)] on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#let_and_return
help: return the expression directly
  |
7 |
8 |
9 |     hex[2..].chars().map(|c| to_binary(c)).collect()
  |

warning: redundant closure found
 --> src/main.rs:7:42
  |
7 |     let to_binary = hex[2..].chars().map(|c| to_binary(c)).collect();
  |                                          ^^^^^^^^^^^^^^^^ help: remove closure as shown: `to_binary`
  |
  = note: #[warn(clippy::redundant_closure)] on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure

There's no reason to return a String here, a &'static str is lighter-weight. See What are the differences between Rust's String and str? for full details, but a String requires a heap allocation, while a &'static str is a reference to some existing data in the compiled binary.

With these changes, all of your tests pass:

fn main() {
    let binary_value = convert_to_binary_from_hex("0x39A7F8");
    println!("Converted: {}", binary_value);
}

fn convert_to_binary_from_hex(hex: &str) -> String {
    hex[2..].chars().map(to_binary).collect()
}

fn to_binary(c: char) -> &'static str {
    match c {
        '0' => "0000",
        '1' => "0001",
        '2' => "0010",
        '3' => "0011",
        '4' => "0100",
        '5' => "0101",
        '6' => "0110",
        '7' => "0111",
        '8' => "1000",
        '9' => "1001",
        'A' => "1010",
        'B' => "1011",
        'C' => "1100",
        'D' => "1101",
        'E' => "1110",
        'F' => "1111",
        _ => "",
    }
}

In fact, deleting all of your code causes your tests to pass. It would be a good idea to add some tests!

Depending on what routes you want to look down next, you could try:

  • to handle strings that do not start with 0x without panicking.
  • to handle upper- and lower-case hex
  • to reduce/avoid string munging yourself
🌐
Rust
docs.rs › hex
hex - Rust
Decodes a hex string into raw bytes.
🌐
Medium
medium.com › @dlcoder › using-hexadecimal-in-rust-a-comprehensive-guide-71160d483286
Using Hexadecimal in Rust: A Comprehensive Guide | by David Li | Medium
May 21, 2023 - In Rust, you can represent hexadecimal literals using the 0x prefix. For example, the following code snippet declares a hexadecimal integer:
🌐
crates.io
crates.io › crates › parse_int
parse_int - crates.io: Rust Package Registry
April 11, 2025 - Parse &str with common prefixes to integer values
🌐
DEV Community
dev.to › pmkroeker › comment › pp26
In rust: // Convert number to hex string. pub fn to_hex (value: i32) ->... - DEV Community
June 3, 2020 - ... // Convert number to hex string. pub fn to_hex (value: i32) -> String { let value = if value > 255 { 255 } else if value < 0 { 0 } else { value }; format!("{:02X}", value) } // Join all hex strings together from rgb input.
🌐
Reddit
reddit.com › r/rust › hex leading 0 issue
r/rust on Reddit: Hex Leading 0 issue
May 14, 2019 -
pub fn hex_to_u64(b: &[u8]) -> Option<u64> {
    let a = std::str::from_utf8(b).ok()?;
    u64::from_str_radix(a, 16).ok()
}

pub fn parse_sha256_to_u64(str: &str) -> Option<[u64; 4]> {
    if str.len() != 64 { return None; }
    let mut out = [0u64; 4];
    for (chunk, slot) in str.as_bytes().chunks(16).zip(out.iter_mut()) {
        *slot = hex_to_u64(chunk)?;
    }
    Some(out)
}

// Impl in Struct U64;4
pub fn to_hex_string(&self) -> String{
    return format!("{:016x}", ByteBuf(self.as_ref()));
}

// That's the string
let contractClientId = "02f101658f665a6e3677995a5a19f37a3f9670b75970305e898459479961249f";

// I convert it to U64;4
let contractClientId_u8 = parse_sha256_to_u64(contractClientId).unwrap();


// Now I convert it back to a String ("Hex" String)
println!("INSURANCE CLIENT ID HASH: {}", contractClientId_u8.to_hex_string());
// Result is 2f101658f665a6e3677995a5a19f37a3f9670b75970305e898459479961249f

can anyone help me fix this issue? I don't know why the 0 disappear :/

I need to do Hex (String) -> U64;4 -> Hex (String)

It needs to be 02f101658f665a6e3677995a5a19f37a3f9670b75970305e898459479961249f, not 2f101658f665a6e3677995a5a19f37a3f9670b75970305e898459479961249f

Top answer
1 of 1
3

A couple of things:

  1. Any time you have a function which could fail, it should return an Option<T>. Ask yourself, if someone calls convert_to_hex_from_binary("foobar") and gets back "", is that reasonable? They will need to manually check that their input makes sense, or that the output makes sense every time. Static checking of these errors is part of the joy of Rust.

With that it mind, change to_hex like so:

fn to_hex(b: &str) -> Option<&str> {
    match b {
        "0000" => Some("0"),
        "0001" => Some("1"),
        "0010" => Some("2"),
        "0011" => Some("3"),
        "0100" => Some("4"),
        "0101" => Some("5"),
        "0110" => Some("6"),
        "0111" => Some("7"),
        "1000" => Some("8"),
        "1001" => Some("9"),
        "1010" => Some("A"),
        "1011" => Some("B"),
        "1100" => Some("C"),
        "1101" => Some("D"),
        "1110" => Some("E"),
        "1111" => Some("F"),
        _ => None,
    }
}
  1. You are iterating over a known range of values to get counter. Instead of using a while loop, you can use a range. Since you're now returning None from to_hex you can now shortcut returning if something is wrong with None.

Your inner loop now looks like this:

let mut hex_string = String::new();
for counter in (0..padded_binary.len()).step_by(4) {
    match to_hex(&padded_binary[counter..counter + 4])
    {
        Some(converted) => hex_string.push_str(converted),
        None => return None
    };
}

Your function signature and return type also need to match Option<String>:

fn convert_to_hex_from_binary(binary: &str) -> Option<String> {
    ...
    Some(hex_string)
}
  1. Your padded_binary definition can be simplified, since repeating "0" zero times is exactly the same as not repeating it.

The definition is simply:

let padded_binary = ["0".repeat(padding_count), binary.to_string()].concat();

A couple of non Rust specific things:

  1. Consider writing some tests.

  2. String representation of binary numbers often begin with '0b'. For example 0b1101 == 13. You might want to consider checking for this prefix on the input string and trimming it.

  3. You may have already thought about this, but consider if you want to trim whitespace or leave it to the function caller.

🌐
TutorialsPoint
tutorialspoint.com › How-to-convert-hex-string-into-int-in-Python
How to convert hex string into int in Python?
April 16, 2025 - The struct module works with binary data and can convert hex strings to integers. First, convert the hex string to bytes, then unpack it using a format specifier. ... import struct hex_str = "1A2D" print("The given hex string is:", hex_str) ...
🌐
crates.io
crates.io › crates › hexstring
hexstring - crates.io: Rust Package Registry
February 11, 2026 - It allows all the common conversion expected from a hexadecimal string :
🌐
Finxter
blog.finxter.com › home › learn python blog › how to convert hex string to integer in python
How to Convert Hex String to Integer in Python - Be on the Right Side of Change
December 2, 2022 - To convert a hexadecimal string to an integer, pass the string as a first argument into Python’s built-in int() function. Use base=16 as a second argument of the int() function to specify that the given string is a hex number.