Skip to content

Instantly share code, notes, and snippets.

@irondoge
Last active July 10, 2016 19:08
Show Gist options
  • Save irondoge/6acc1051d4a418b186872d00028f6143 to your computer and use it in GitHub Desktop.
Save irondoge/6acc1051d4a418b186872d00028f6143 to your computer and use it in GitHub Desktop.
simple base conversion with buffer [compilation: gcc -W -Wall -Wextra -std=c89 base_buffer.c]
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
# define push_front(buff, c) (memmove(buff + 1, buff, (strlen(buff) + 2)), *buff = c)
char *convert(int o, char *buff, char const *base)
{
*buff = 0;
while (o > 0)
{
push_front(buff, base[o % strlen(base)]);
o /= strlen(base);
}
return (buff);
}
int main(int ac, char **av)
{
int o;
char buff[sizeof(int) * 8 + 1];
if (ac != 2)
return (1);
o = atoi(av[1]);
printf("%s\n", convert(o, buff, "0123456789ABCDEF"));
printf("%s\n", convert(o, buff, "01"));
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment