Thursday, June 22, 2006

 

printf() and 64-bit integers

In the last post we talked about scanf(), so perhaps it would be proper now to discuss printf().

Good and reasonably brief manual page could be found here; then make sure to check Microsoft-specific formats here.

Some interesting features are there, e.g. you can use <'> format (single quote) to enable locale-specific number output (has no effect in C locale); you can also refer to specific argument by number, specify format width as a separate argument, and so on.

Let's consider one specific task to print some (large) 64-bit value. The basic problem is that you must know (1) what (integer) type to use to represent (at least) 64-bit integers, and (2) what printf() format does this type correspond to, if any.

On UNIX platforms long usually correspond to "machine word" (that is to say, has same size as pointer) so on 64-bit UNIX long is 64-bit and the following code:

printf ( "2^63 = %lu\n", 1L << 63 );

will print 2^63 = 9223372036854775808.

On 32-bit UNIX systems long is 32-bit but long long is 64-bit, and then the following code will work as expected:

printf ( "2^63 = %llu\n", (long long)1 << 63 )

(Gnu gcc understands 1LL, but I am not sure if other compilers do).

On Windows, however (with Microsoft compiler) approach is different and size of basic types does not change with CPU and so long is always 32-bit (same as int). Thus, in older Visual C++ systems you have to write:

printf ( "2^63 = %I64u\n", (__int64)1 << 63 );

... while in Visual .NET the above example with "long long" will work.

Labels: , ,


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?