In this article, we are going to learn how to convert hexadecimal to decimal integer in Rust. In rust, this is very simple to do the conversion or find the equivalent number. Rust provided the implicit type conversion where we can specify the type of variable and when we assign the value to it converts this data to the data type of the variable.
1. Rust Conversion hexadecimal to decimal integer
In this first example, we are going to see this conversion or you can say type formatting. First, we are creating a variable with the name ‘num’. The next step is assigning it a hexadecimal number. Now in Rust, you can add the prefix 0x to represent a hexadecimal number, for example, “0xA01” is a hexadecimal number for the Rust compiler.
Once we assign this number to a variable num and during this assignment we are specifying the type of num as i32. This would mean this hexadecimal number will be assigned to a num in the form of a 32-bit integer.
Let us see this with the help of the below code example:
fn main()
{
let num:i32=0xA01;
println!("Decimal number: {}",num);
}
Output:
rustc -o main main.rs
./main
Decimal number: 2561
2. Rust Conversion hexadecimal number to decimal integer
In this second, example, we are going to see how to convert a hexadecimal number to a decimal number with the help of some functions. We are taking a hexadecimal number with a “0x” prefix attached to it.First we will remove this prefix “0x” by using the trim_start_matches() function. This function trims the desired part of a string. Once we have the hexadecimal number without the “0x” part then we are using the from_str_radix() function to convert this to an integer.
Let us see this code in action.
use std::i64;
fn main()
{
let hex_numwith_hexprefix = "0xf1";
let hexnum = hex_numwith_hexprefix.trim_start_matches("0x");
let intvalue = i64::from_str_radix(hexnum, 16);
println!("The Decimal Number is {:?}", intvalue);
}
Output
rustc -o main main.rs
./main
The Decimal Number is Ok(241)