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) ...
🌐
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 ::Err: std::fmt::Debug { let value = value.trim(); if value.starts_with("0x") { ::from_str_radix(value.strip_prefix("0x").unwrap(), 16).ok().unwrap() } else { value.parse:: ().unw...
🌐
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.
🌐
Programming Idioms
programming-idioms.org › idiom › 142 › hexadecimal-digits-of-an-integer › 2346 › rust
Hexadecimal digits of an integer, in Rust
digits = hexdigits[:16] def parse(value): if value < 16: return digits[value] n, index = divmod(value, 16) return parse(n) + digits[index] s = parse(x) ... Do you know the best way to do this in your language ? New implementation... ... template <typename I> std::string n2hexstr(I w, size_t ...
Find elsewhere
🌐
Rust
docs.rs › hex
hex - Rust
Decodes a hex string into raw bytes.
🌐
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.
🌐
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 › hexstring
hexstring - crates.io: Rust Package Registry
February 11, 2026 - It allows all the common conversion expected from a hexadecimal string :
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.

🌐
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 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.
🌐
Rust
doc.rust-lang.org › std › fmt › trait.UpperHex.html
UpperHex in std::fmt - Rust
The UpperHex trait should format its output as a number in hexadecimal, with A through F in upper case. For primitive signed integers (i8 to i128, and isize), negative values are formatted as the two’s complement representation.