How to convert an integer to a string in base b with Rust

2 Answers

0 votes
fn to_base(mut num: u32, base: u32) -> String {
    assert!(base >= 2 && base <= 36, "Base must be between 2 and 36");
    let mut result = String::new();
    let digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    while num > 0 {
        let remainder = (num % base) as usize;
        result.push(digits.chars().nth(remainder).unwrap());
        num /= base;
    }

    result.chars().rev().collect()
}

fn main() {
    let number = 255;
    let base = 16;

    let result = to_base(number, base);
    println!("Number {} in base {} = {}", number, base, result);
}




/*
run:

Number 255 in base 16 = FF

*/

 



answered Aug 18, 2025 by avibootz
0 votes
fn main() {
    let number = 255;

    // Binary
    let binary = format!("{:b}", number);
    println!("Binary: {}", binary);

    // Octal
    let octal = format!("{:o}", number);
    println!("Octal: {}", octal);

    // Hexadecimal
    let hexadecimal = format!("{:X}", number);
    println!("Hexadecimal: {}", hexadecimal);
}





/*
run:

Binary: 11111111
Octal: 377
Hexadecimal: FF

*/

 



answered Aug 18, 2025 by avibootz
...