How to convert uint64_t value to const char string?

See in one situation

uint64_t trackuid = 2906622092;

Now I want to pass this value to one function, where the function argument const char*

func(const char *uid)
{
   printf("uid is %s",uid);
}

It should print

uid is 2906622092 

How can i do this?

+5
source share
3 answers
// length of 2**64 - 1, +1 for nul.
char buff[21];

// copy to buffer
sprintf(buff, "%" PRIu64, trackuid);

// call function
func(buff);

This requires C99, but my memory says that the MS compiler does not PRIu64. ( PRIu64located at inttypes.h.) YMMV.

+8
source

Use snprintfto convert numbers to strings. For integer types from the header, stdint.huse format macros from inttypes.h.

#define __STDC_FORMAT_MACROS // non needed in C, only in C++
#include <inttypes.h>
#include <stdio.h>

void func(const char *uid)
{
    printf("uid is %s\n",uid);
}

int main()
{
    uint64_t trackuid = 2906622092;

    char buf[256];
    snprintf(buf, sizeof buf, "%"PRIu64, trackuid);

    func(buf);

    return 0;
}
+8
source
char buf[40];
memset (buf, 0, sizeof(buf));
snprintf (buf, sizeof(buf)-1, "%llu", (unsigned long long) trackuid);
func(buf);

, sizeof(unsigned long long) == sizeof(uint64_t)

- "%"PRIu64

+1