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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,011 questions

51,958 answers

573 users

How to convert a number to any base in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <algorithm>

std::string to_base(unsigned int n, unsigned int base) {
    static const std::string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    if (base < 2 || base > 36)
        throw std::invalid_argument("Base must be between 2 and 36");

    if (n == 0)
        return "0";

    std::string result;

    while (n > 0) {
        unsigned int remainder = n % base;
        result.push_back(digits[remainder]);
        n /= base;
    }

    std::reverse(result.begin(), result.end());
    
    return result;
}

int main() {
    try {
        unsigned int number = 255;

        std::cout << number << " in base 2  = " << to_base(number, 2)  << "\n";
        std::cout << number << " in base 8  = " << to_base(number, 8)  << "\n";
        std::cout << number << " in base 16 = " << to_base(number, 16) << "\n";
        std::cout << number << " in base 36 = " << to_base(number, 36) << "\n";
    }
    catch (const std::exception& ex) {
        std::cerr << "Error: " << ex.what() << "\n";
    }
}



/*
run:

255 in base 2  = 11111111
255 in base 8  = 377
255 in base 16 = FF
255 in base 36 = 73

*/

 



answered 4 hours ago by avibootz
...