Converting a hexadecimal string to a decimal integer

32,086

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:

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);
}
Share:
32,086

Related videos on Youtube

tsf144
Author by

tsf144

Updated on July 09, 2022

Comments

  • tsf144
    tsf144 almost 2 years

    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?

  • tsf144
    tsf144 over 8 years
    That's great, thanks! Just to clarify, the '[2..]' is how you skip the first two spaces? (like over '0' and 'x')
  • Vladimir Matveev
    Vladimir Matveev over 8 years
    @tsf144, it is slicing syntax. &raw[2..] is a substring of raw starting at the second byte of raw.
  • Shepmaster
    Shepmaster over 8 years
    @tsf144 Just what Vladimir said. The important part is that it is bytes. In this case, it looks like you have ASCII-encoded strings, so one character == one byte.
  • Jake Ireland
    Jake Ireland about 3 years
    Does this code fail on a 32-bit machine? You can do the same thing but replacing i64 with isize so that it supports the architecture of the machine you run it on.
  • Shepmaster
    Shepmaster about 3 years
    @JakeIreland no, this does not fail on a 32-bit machine.