Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,569 questions

56,787 answers

573 users

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
...