Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A funny thing with sprintf

I'm so confused with sprintf that a funny problem with different platfrom. Code :

int main () 
{
    char sql[1024];
    uint32_t app_id = 32;
    uint64_t task_id = 64;
    sprintf(sql, "%u, %u", task_id, app_id);
    printf ("%s\n", sql);
    return 0;
}

The result in console (MSVC2010 debug/release): 64, 0

But the same code in console(CentOS64 gcc4.4.6): 64, 32

Any guy will help me, tks!

-------------updated--------------------------

Thanks guys. I have read this article: sprintf for unsigned _int64

Actually, PRIu64 in "inttypes.h" defined: I64uwhich is not supported on windows. So I can write like this:

sprintf(sql, "%I64u, %I32u", task_id, app_id);
like image 386
wells Avatar asked Jun 12 '13 12:06

wells


2 Answers

Use %llu format string for task_id in sprintf()as follows:

sprintf(sql, "%llu, %u", task_id, app_id);
//             ^
//            for: long long unsigned int

Edit: As @Simonc suggested its better to use: PRIu32 and PRIu64 macros defined in <inttypes.h> (as you have Linux tag) do like:

sprintf(sql, "%"PRIu64", %"PRIu32"", task_id, app_id);
//               ^           ^
//       for:   uint64_t    uint32_t  
like image 84
Grijesh Chauhan Avatar answered Nov 13 '22 23:11

Grijesh Chauhan


Format string %lu won't work on 32-bit machines, where a 64-bit variable is long long.

Use %llu for 64-bit instead:

#include <stdio.h>
#include <stdlib.h>
#include <linux/types.h>
#include <stdint.h>

int main () 
{
    char sql[1024];
    uint32_t app_id = 32;
    uint64_t task_id = 64;
    sprintf(sql, "%llu, %u", task_id, app_id);
    printf ("%s\n", sql);
    return 0;
}
like image 25
Claudio Avatar answered Nov 13 '22 23:11

Claudio