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 <stdio.h>
#include <string.h>

void to_base(unsigned int n, unsigned int base, char *out) {
    static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char buffer[64];   // temporary buffer (enough for 32-bit ints in base 2)
    int i = 0;

    if (base < 2 || base > 36) {
        out[0] = '\0';
        return;
    }

    if (n == 0) {
        out[0] = '0';
        out[1] = '\0';
        return;
    }

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

    // reverse into output
    for (int j = 0; j < i; j++) {
        out[j] = buffer[i - j - 1];
    }
    out[i] = '\0';
}



int main() {
    char result[64];

    to_base(25, 2, result);
    printf("25 in base 2: %s\n", result);

    to_base(25, 8, result);
    printf("25 in base 8: %s\n", result);

    to_base(25, 16, result);
    printf("25 in base 16: %s\n", result);

    to_base(255, 36, result);
    printf("255 in base 36: %s\n", result);

    return 0;
}



/*
run:

25 in base 2: 11001
25 in base 8: 31
25 in base 16: 19
255 in base 36: 73

*/

 



answered 4 hours ago by avibootz

Related questions

...