将十六进制字符串转换为十进制 [英] Converting hexadecimal string to decimal
本文介绍了将十六进制字符串转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在写一个Rust程序,读取I2C总线并保存数据。当我读I2C总线时,我得到了十六进制值,如 0x11
, 0x22
等。
现在,我只能将它作为一个字符串处理并保存。有没有办法我可以解析成一个整数?有没有内置的函数?
解决方案
您想使用 from_str_radix
。它在整数类型上实现。
使用std :: i64;
fn main(){
let z = i64 :: from_str_radix(1f,16);
println!({:?},z);
$ b如果你的字符串实际上有 0x
前缀,那么你需要跳过它们。最快的方法是:
$ p $ 使用std :: i64;
fn main(){
let raw =0x1f;
let z = i64 :: from_str_radix(& raw [2 ..],16);
println!({:?},z);
}
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?
解决方案
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 quickest way to do that is:
use std::i64;
fn main() {
let raw = "0x1f";
let z = i64::from_str_radix(&raw[2..], 16);
println!("{:?}", z);
}
这篇关于将十六进制字符串转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文