Last active
July 10, 2016 19:06
-
-
Save irondoge/d7cc5eac20e80de1136a7c519d3dc50e to your computer and use it in GitHub Desktop.
simple base conversion with realloc [compilation: gcc -W -Wall -Wextra -std=c89 base_realloc.c]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <string.h> | |
#include <stdio.h> | |
void push_front(char **str, char c) | |
{ | |
char *ret; | |
ret = malloc(sizeof(char) * (strlen(*str) + 2)); | |
*ret = c; | |
memmove(ret + 1, *str, strlen(*str)); | |
free(*str); | |
*str = ret; | |
} | |
char *convert(int o, char const *base) | |
{ | |
char *ret; | |
ret = malloc(sizeof(char)); | |
*ret = 0; | |
while (o > 0) | |
{ | |
push_front(&ret, base[o % strlen(base)]); | |
o /= strlen(base); | |
} | |
return (ret); | |
} | |
int main(int ac, char **av) | |
{ | |
int o; | |
if (ac != 2) | |
return (1); | |
o = atoi(av[1]); | |
printf("%s\n", convert(o, "0123456789ABCDEF")); | |
printf("%s\n", convert(o, "01")); | |
return (0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment