Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert uint64_t value in const char string?

Tags:

c

See in one situation

uint64_t trackuid = 2906622092;

Now I want to pass this value in one function where function argument is const char*

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

This should print

uid is 2906622092 

How can I do this?

like image 442
Jeegar Patel Avatar asked Nov 30 '11 08:11

Jeegar Patel


2 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, however, my memory says the MS compiler doesn't have PRIu64. (PRIu64 is in inttypes.h.) YMMV.

like image 129
Thanatos Avatar answered Nov 12 '22 01:11

Thanatos


Use snprintf to convert numbers to strings. For integer types from stdint.h header use the 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;
}
like image 37
Maxim Egorushkin Avatar answered Nov 12 '22 02:11

Maxim Egorushkin