To convert a number from base 2 (binary) to base 10 (decimal) in Rust, you can use the standard library's i32::from_str_radix
function. This function takes two arguments: the first is the string representation of the number you want to convert, and the second is the base of the input number (in this case 2).
Here's the code to perform the conversion:
main.rs261 chars6 lines
In the above code, we define the binary string "1010"
, which represents the number we want to convert.
Then we use the i32::from_str_radix
function to convert this binary string to a decimal number. We pass in the binary string as the first argument, and the number 2
as the second argument, to indicate that the input number is in base 2.
Finally, we print out the decimal representation of the binary number using the println!
macro.
This code should output: Decimal representation of 1010 is 10
gistlibby LogSnag