Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <assert.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <limits.h>
- #define MAX_BASE() strlen(alphabet)
- static char const *alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- static unsigned int ullong2str(char [], unsigned long long, unsigned int);
- static unsigned long long str2ullong(char const [], unsigned int);
- static char *convertToNewBase(char const [], unsigned int, unsigned int);
- static long indexOf(char const [], char);
- static unsigned long long power(unsigned int, unsigned int);
- static void reverse(char []);
- int main(void)
- {
- char *decimal = "28697";
- char *binary = convertToNewBase(decimal, 10, 2);
- printf("%s (base 10) = %s (base 2)n", decimal, binary);
- perror(NULL);
- free(binary);
- }
- /*
- ===============
- char *convertToNewBase(char [], unsigned int, unsigned int);
- The function converts an unsigned integer number from the source base to
- destination base. The function allocates a buffer of length large enough
- to store the result and returns it. If an error occurs the function
- returns NULL.
- ===============
- */
- char *convertToNewBase(char const s[], unsigned int src, unsigned int dest)
- {
- assert(s);
- assert(src >= 2 && src <= MAX_BASE());
- assert(dest >= 2 && dest <= MAX_BASE());
- errno = 0;
- unsigned long long const n = str2ullong(s, src);
- if (errno != 0)
- return NULL;
- unsigned int const resultLength = ullong2str(NULL, n, dest);
- char *result = calloc(resultLength + 1, 1);
- if (result == NULL)
- return NULL;
- ullong2str(result, n, dest);
- return result;
- }
- /*
- ===============
- unsigned long long ullong2str(char [], unsigned long long, unsigned int);
- The function converts an unsigned integer value to a null-terminated string
- using the specified base and stores the result in the array given by the first
- parameter. It assumes that size of the array is large enough to store the
- result.
- The function returns length of the result string. If the first parameter is
- NULL nothing is written, however the return value is still calculated and
- returned.
- ===============
- */
- unsigned int ullong2str(char out[], unsigned long long n, unsigned int base)
- {
- assert(base >= 2 && base <= MAX_BASE());
- unsigned int i = 0;
- do {
- if (out != NULL)
- out[i] = alphabet[n % base];
- n /= base;
- i++;
- } while (n);
- if (out != NULL) {
- out[i] = '