Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

parsing - Converting a hexadecimal string to a decimal integer

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...