Adding a new specifier involves re-writing printf()
or crafting your own function that handles the new specifier as well as printf()
and calling that. Both of these approaches are difficult.
An alternative is to use "%s"
and craft your own function that forms a string.
With C99 or later, use a compound literal to form the needed buffer space.
#include <stdio.h>
#define MYIP_N 16
#define MYIP(ip) myip((char [MYIP_N]){""}, (ip))
char *myip(char *dest, int ip) {
snprintf(dest, MYIP_N, "%d.%d.%d.%d", (ip >> 24) & 255, (ip >> 16) & 255,
(ip >> 8) & 255, (ip >> 0) & 255);
return dest;
}
int main(void) {
int ip1 = 0x01020304;
int ip2 = 0x05060708;
printf("%s %s\n", MYIP(ip1), MYIP(ip2));
return 0;
}
Output
1.2.3.4 5.6.7.8
This works with printf()
or fprintf()
, sprintf()
, even puts()
puts(MYIP(ip1));
1.2.3.4