将十六进制字符串转换为十进制整数 [英] Converting a hexadecimal string to a decimal integer

查看:162
本文介绍了将十六进制字符串转换为十进制整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Rust程序,该程序会读取I2C总线并保存数据.当我读取I2C总线时,会得到诸如0x110x22等的十六进制值.

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?

推荐答案

在大多数情况下,您希望一次解析多个十六进制字节.在这种情况下,请使用十六进制的盒子.

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

您要使用 from_str_radix .它是在整数类型上实现的.

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

如果您的字符串实际上具有0x前缀,那么您将需要跳过它们.最好的方法是通过 trim_start_matches :

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

这篇关于将十六进制字符串转换为十进制整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆