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.

39,895 questions

51,826 answers

573 users

How to convert an integer to a string in base b with C++

1 Answer

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

std::string intToBase(int number, int base) {
    if (base < 2 || base > 36) {
        throw std::invalid_argument("Base must be in the range [2, 36]");
    }

    const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    bool isNegative = (number < 0 && base == 10); // Handle negative numbers for base 10
    number = std::abs(number);

    std::string result;
    do {
        result += digits[number % base];
        number /= base;
    } while (number > 0);

    if (isNegative) {
        result += '-';
    }

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

int main() {
    int number = 255;
    
    std::cout << number << " in base 2 = " << intToBase(number, 2) << std::endl;   
    std::cout << number << " in base 8 = " << intToBase(number, 8) << std::endl;   
    std::cout << number << " in base 16 = " << intToBase(number, 16) << std::endl;
    std::cout << number << " in base 36 = " << intToBase(number, 36) << std::endl; 
}



/*
run:

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

*/

 



answered Aug 17, 2025 by avibootz
edited Aug 17, 2025 by avibootz
...