Answers for "convert decimal to binary rust"

0

convert decimal to binary rust

fn to_binary(mut decimal: i32) -> i32 {
    if decimal == 0 {
        decimal
    } else {
        let mut bits = String::new();
        while decimal > 0 {
            if decimal % 2 == 0 {
                bits.push_str("0");
            } else {
                bits.push_str("1");
            }
            decimal /= 2;
        }
        // reverse the bits
        match bits.chars().rev().collect::<String>().parse() {
            Ok(num) => num,
            Err(_e) => panic!("Something went wrong"),
        }
    }
}
Posted by: Guest on October-17-2021

Code answers related to "convert decimal to binary rust"

Browse Popular Code Answers by Language