In this article, we are going to learn a basic method to convert a binary number to its equivalent decimal integer number. 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 binary number to a 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 binary number. Now in Rust, you can add the prefix 0b to represent a binary number, for example, “0b10110101” is a binary 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 binary number will be assigned to 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=0b10110101;
println!("The Decimal equivalent number is: {}",num);
}
Output
rustc -o main main.rs
./main
The Decimal equivalent number is: 181
2. Rust parse binary number to decimal
In this second, example, we are going to see how to convert a binary number to a decimal number with the help of some functions.
We are taking a binary number with 0s and 1s. Once we have the binary number then we are using the from_str_radix() function to convert this to an integer. Let us see this code in action.
fn main()
{
let bin_number = "10101010101";
let int_number = isize::from_str_radix(bin_number, 2).unwrap();
println!("The Decimal equivalent is {}", int_number);
}
Output
rustc -o main main.rs
./main
The Decimal equivalent is 1365