convert a number from base 2 to base 16 in rust

To convert a binary number to a hexadecimal number in Rust, you can use the u32::from_str_radix function to parse the binary number from a string and then format the resulting u32 as a hexadecimal string using the format! macro.

Here's an example function that takes a binary string and returns a hexadecimal string:

main.rs
fn binary_to_hex(binary: &str) -> String {
    let n = u32::from_str_radix(binary, 2).unwrap();
    format!("{:X}", n) // X format specifier formats the number in uppercase hexadecimal
}
187 chars
5 lines

You can call this function like this:

main.rs
let binary = "110101101"; // binary equivalent of decimal 437
let hex = binary_to_hex(binary);
println!("{}", hex); // prints "1B5"
132 chars
4 lines

Note that the input binary string should only contain 0 and 1 characters, and the function assumes that the binary number is unsigned.

gistlibby LogSnag