Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf for unsigned _int64

Tags:

I am having following code. output of second %d in sprintf is always shown as zero. I think i am specifying wrong specifiers. Can any one help me in getting write string with right values. And this has to achieved in posix standard. Thanks for inputs

void main() {     unsigned _int64 dbFileSize = 99;     unsigned _int64 fileSize = 100;     char buf[128];     memset(buf, 0x00, 128);     sprintf(buf, "\nOD DB File Size = %d bytes \t XML file size = %d bytes", fileSize, dbFileSize);     printf("The string is %s ", buf);     } 

Output:

The string is OD DB File Size = 100 bytes      XML file size = 0 bytes  
like image 457
venkysmarty Avatar asked Feb 28 '11 10:02

venkysmarty


People also ask

How do you use unsigned long long int?

The maximum value that can be stored in unsigned long long int is stored as a constant in <climits> header file whose value can be used as ULLONG_MAX. The minimum value that can be stored in unsigned long long int is zero. In case of overflow or underflow of data type, the value is wrapped around.

What is LLU C?

%lli or %lld. Long long. %llu. Unsigned long long.

What is the format specifier for unsigned long int?

The correct specifier for unsigned long is %lu .

What is PRIu64?

PRIu64 is a format specifier, introduced in C99, for printing uint64_t , where uint64_t is (from linked reference page): unsigned integer type with width of ... 64 bits respectively (provided only if the implementation directly supports the type)


2 Answers

I don't know what POSIX has to say about this, but this is nicely handled by core C99:

#include <stdio.h> #include <inttypes.h>  int main(void) {     uint64_t dbFileSize = 99;     uint64_t fileSize = 100;     char buf[128];     memset(buf, 0x00, 128);     sprintf( buf, "\nOD DB File Size = %" PRIu64 " bytes \t"                   " XML file size = %" PRIu64 " bytes\n"                   , fileSize, dbFileSize );     printf( "The string is %s\n", buf ); } 

If your compiler isn't C99 compliant, get a different compiler. (Yes, I'm looking at you, Visual Studio.)

PS: If you are worried about portability, don't use %lld. That's for long long, but there are no guarantees that long long actually is the same as _int64 (POSIX) or int64_t (C99).

Edit: Mea culpa - I more or less brainlessly "search & replace"d the _int64 with int64_t without really looking at what I am doing. Thanks for the comments pointing out that it's uint64_t, not unsigned int64_t. Corrected.

like image 114
DevSolar Avatar answered Oct 19 '22 23:10

DevSolar


You need to use %I64u with Visual C++.

However, on most C/C++ compiler, 64 bit integer is long long. Therefore, adopt to using long long and use %llu.

like image 29
Shamim Hafiz - MSFT Avatar answered Oct 19 '22 22:10

Shamim Hafiz - MSFT