80

I'm writing a Rust program that reads off of an I2C bus and saves the data. When I read the I2C bus, I get hex values like 0x11, 0x22, etc.

Right now, I can only handle this as a string and save it as is. Is there a way I can parse this into an integer? Is there any built in function for it?

2 Answers 2

128

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);
}
Sign up to request clarification or add additional context in comments.

10 Comments

That's great, thanks! Just to clarify, the '[2..]' is how you skip the first two spaces? (like over '0' and 'x')
@tsf144, it is slicing syntax. &raw[2..] is a substring of raw starting at the second byte of raw.
@JakeIreland no, this does not fail on a 32-bit machine.
Note that trim_start_matches removes the prefix repeatedly, so that would also parse 0x0x0x1f. You can use strip_prefix to remove only once, but will need to differentiate the two cases.
@AthulMuralidhar it's not currently possible to call trait methods for compile-time values, so there is no direct solution.
|
-3

strip_prefix was mentioned earlier, and actually isn't as much trouble to use as it might seem at a casual glance. It can be nested and does the expected thing. Playground Link


fn trimhex(s: &str) -> &str {
    s.strip_prefix("0x").unwrap_or(s.strip_prefix("0X").unwrap_or(s))
}

fn main() {
    println!("{}", trimhex("0123"));
    println!("{}", trimhex("0x01"));
    println!("{}", trimhex("0X23"));
    // only the first leading 0[xX] is removed
    println!("{}", trimhex("0x0x45"));
    println!("{}", trimhex("0x0X67"));
    println!("{}", trimhex("0X0x89"));
    println!("{}", trimhex("0X0Xab"));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.