Skip to content

Instantly share code, notes, and snippets.

@mitake
Created October 20, 2012 17:51
Show Gist options
  • Save mitake/3924195 to your computer and use it in GitHub Desktop.
Save mitake/3924195 to your computer and use it in GitHub Desktop.
easy string format without runtime memory allocation, example of IP address
#include <stdio.h>
#include <string.h>
#define BUF_NUM 32
#define BUF_LEN 16
static char *format(int val)
{
static char buf[BUF_NUM][BUF_LEN];
static int buf_i;
int i;
char *ret, *b = buf[buf_i++];
ret = b;
bzero(b, BUF_LEN);
for (i = 0; i < 3; i++) {
b += sprintf(b, "%d.", val & 0xff);
val >>= 8;
}
sprintf(b, "%d", val & 0xff);
buf_i %= BUF_NUM;
return ret;
}
int main(void)
{
printf("255.255.255.255: %s, 127.0.0.1: %s, 10.0.0.1: %s\n",
format(0xffffffff), format(0x0100007f), format(0x0100000a));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment