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

Hex Leading 0 issue

The zeo disappears, because you reserve space for 16 hex chars only, but u require 64 hex chars. Please also verify if sha256 has can really be stored in an u64 integer!

More on reddit.com
🌐 r/rust
7
4
May 14, 2019
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
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
rust - Decimal number to hexadecimal string - Stack Overflow
Does Rust have a set of functions that make converting a decimal integer to a hexadecimal string easy? I have no trouble converting a string to an integer, but I can't seem to figure out the opposite. More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › rust-lang › rfcs › issues › 1098
Parsing string to integer accepting '0x' + hexadecimal · Issue #1098 · rust-lang/rfcs
April 29, 2015 - In many cases, it is useful for a program that parses integers (e.g. from the command line) to accept both decimal and hexadecimal constants, by letting the user prefix the latter with 0x. Currently, FromStr::from_str (also the destination of str::parse) only accepts base 10; from_str_radix allows an arbitrary base to be specified, but doesn't have any special magic to parse prefixes. If I were writing from_str from scratch, I would suggest having it accept 0x, perhaps along with 0o and 0b like Rust ...
Author: rust-lang
🌐
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, ...
🌐
Programming Idioms
programming-idioms.org › idiom › 142 › hexadecimal-digits-of-an-integer › 2346 › rust
Hexadecimal digits of an integer, in Rust
Obj-C · PHP · 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 ·
🌐
Rust Documentation
doc.rust-lang.org › beta › std › char › fn.from_digit.html
from_digit in std::char - Rust
Converts a digit in the given radix to a `char`. Use `char::from_digit` instead.
🌐
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:
🌐
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

Find elsewhere
🌐
Rust
docs.rs › hex
hex - Rust
Encoding and decoding hex strings. For most cases, you can simply use the decode, encode and encode_upper functions.
🌐
Rust
doc.rust-lang.org › std › fmt › trait.UpperHex.html
UpperHex in std::fmt - Rust
use std::fmt; struct Length(i32); impl fmt::UpperHex for Length { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val = self.0; fmt::UpperHex::fmt(&val, f) // delegate to i32's implementation } } let l = Length(i32::MAX); assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF"); assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF"); ... Formats the value using the given formatter. This function should return Err if, and only if, the provided Formatter returns Err. String formatting is considered an infallible operation; this function only returns a Result because writing to the underlying stream might fail and it must provide a way to propagate the fact that an error has occurred back up the stack.
🌐
FriendlyUsers Tech Blog
friendlyuser.github.io › posts › tech › rust › Using_Hexadecimal_in_Rust_A_Comprehensive_Guide
Using Hexadecimal in Rust A Comprehensive Guide - FriendlyUsers Tech Blog
To convert a hexadecimal string to a decimal integer, you can use the u32::from_str_radix method (or any other appropriate integer type depending on the range of your hexadecimal value):
🌐
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.
🌐
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 Documentation
doc.rust-lang.org › stable › rust-by-example › primitives › literals.html
Literals and operators - Rust By Example
Integers 1, floats 1.2, characters 'a', strings "abc", booleans true and the unit type () can be expressed using literals. Integers can, alternatively, be expressed using hexadecimal, octal or binary notation using these prefixes respectively: 0x, 0o or 0b. Underscores can be inserted in numeric literals to improve readability, e.g.
🌐
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 :
🌐
Rust Programming Language
users.rust-lang.org › t › how-would-i-store-hexedecimal-values-in-a-variable › 45545
How would I store hexedecimal values in a variable? - The Rust Programming Language Forum
July 8, 2020 - extern crate hex; fn main() { let blue: u32 = hex::decode("0c1047"); // Error over here } So I want blue to store #0c1047 this hexadecimal value inside blue (here is the color picker site https://duckduckgo.com/?q=color+picker&t=hk&ia=answer. Is there a way to directly store hexadecimal values or do I have to store it in a decoded fashion or something.
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 › latest › hex › fn.decode.html
decode in hex - Rust
Available on crate feature alloc only. ... Decodes a hex string into raw bytes.
🌐
Exercism
exercism.org › tracks › rust › exercises › hexadecimal
Hexadecimal in Rust on Exercism
Convert a hexadecimal number, represented as a string (e.g. "10af8c"), to its decimal equivalent using first principles (i.e.