Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I write my own new format specifier in C?

Is it possible to write a new format specifier in C? For example, let's say, %g is a format specifier which prints the ip address in A.B.C.D format from the unsigned integer equivalent.

int ip_addr = Some integer

printf("ip address = %g", ip_addr);

output: prints ip address in A.B.C.D format

like image 448
Abhishek Sagar Avatar asked Dec 24 '22 10:12

Abhishek Sagar


1 Answers

You would have to reimplement the printf function (more precisely its format parsing function). What you can do is wrap printf inside a function that supports ip addresses or do this:

#define FMT_IP "%d.%d.%d.%d"
#define FMT_IP_ARG(ip) getA(ip), getB(ip), getC(ip), getD(ip)

Where the getX functions or macros get the X part of the given integer representing an IP address.

Then:

printf("ip address = " FMT_IP "\n", FMT_IP_ARG(ip));
like image 90
mikedu95 Avatar answered Dec 27 '22 11:12

mikedu95