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,870 questions

51,793 answers

573 users

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

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void intToBase(int number, int base, char *output) {
    const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char buffer[65]; // Enough for base 2 of a 64-bit number
    int i = 0;

    if (number == 0) {
        strcpy(output, "0");
        return;
    }

    int isNegative = number < 0;
    unsigned int n = isNegative ? -number : number;

    while (n > 0) {
        buffer[i++] = digits[n % base];
        n /= base;
    }

    if (isNegative) {
        buffer[i++] = '-';
    }

    buffer[i] = '\0';

    // Reverse the string
    for (int j = 0; j < i; j++) {
        output[j] = buffer[i - j - 1];
    }
    output[i] = '\0';
}

int main() {
    int number = 255;
    char result[65];

    int bases[] = {2, 8, 16, 36};
    
    for (int i = 0; i < 4; i++) {
        int base = bases[i];
        intToBase(number, base, result);
        printf("%d in base %d = %s\n", number, base, result);
    }

    return 0;
}



/*
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

Related questions

...