Peter Smit
Peter Smit

Reputation: 28716

How to change my sprintf format string, based on size of long

I would like to read in some uint64_t values from a hexadecimal string with printf and scanf.

Not all the platforms that I use have the same size for long or long long, so if I use a format string like "%llx" it gives warnings on platforms with a long long of 128 bits and "%lx" will give warnings on platforms with long long being 64 bits (and long smaller).

My first thought was to define the format string with a macro, but sizeof is not supported in macro expressions.

Is there a way to define my format string so that it will work on any platform, preferably without warnings?

Upvotes: 2

Views: 228

Answers (1)

M.M
M.M

Reputation: 141554

The format string for uint64_t is defined by a macro PRIu64

For example:

uint64_t foo = 0;

printf("%" PRIu64 "\n", foo);

Similar format strings exist for scanf, in this case SCNu64. These are macros defined in <inttypes.h>.

Upvotes: 5

Related Questions