convert a number from base 2 to base 8 in rust

To convert a binary number (base 2) to octal (base 8) in Rust, you can follow these steps:

  1. Obtain the binary number and store it as a string
  2. Split the string into groups of three digits from right to left. If the final group has less than three digits, add leading zeros.
  3. Convert each group of three binary digits to its octal equivalent.
  4. Combine the octal digits to form the final octal number.

Here is the code for the function:

main.rs
fn binary_to_octal(binary_num: &str) -> String {
    // Split the binary number into groups of 3 digits (starting from right)
    let binary_groups = binary_num
        .chars()
        .rev()
        .collect::<String>()
        .as_bytes()
        .chunks(3)
        .map(|chunk| std::str::from_utf8(chunk).unwrap())
        .collect::<Vec<_>>();
    
    // Convert each binary group to its octal equivalent and combine
    let octal_num = binary_groups.iter()
        .map(|&group| i32::from_str_radix(&group.to_owned(), 2).unwrap())
        .rev()
        .fold(String::new(), |acc, &octal| format!("{}{}", acc, octal));

    // Return the octal number
    octal_num
}
674 chars
21 lines

You can call this function by passing the binary number as a string argument:

main.rs
let binary_num = "10111010";
let octal_num = binary_to_octal(binary_num);
println!("The octal conversion of {} is {}", binary_num, octal_num);
143 chars
4 lines

This will output:

main.rs
The octal conversion of 10111010 is 272
40 chars
2 lines

gistlibby LogSnag