简体   繁体   English

如何在const char字符串中转换uint64_t值?

[英]how to convert uint64_t value in const char string?

See in one situation在一种情况下查看

uint64_t trackuid = 2906622092;

Now I want to pass this value in one function where function argument is const char*现在我想在一个函数中传递这个值,其中函数参数是const char*

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

This should print这应该打印

uid is 2906622092 

How can I do this?我怎样才能做到这一点?

// 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 .这需要 C99,但是,我的记忆说 MS 编译器没有PRIu64 ( PRIu64 is in inttypes.h .) YMMV. PRIu64inttypes.h 。) YMMV。

Use snprintf to convert numbers to strings.使用snprintf将数字转换为字符串。 For integer types from stdint.h header use the format macros from inttypes.h .对于stdint.h标头中的整数类型,请使用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;
}
char buf[40];
memset (buf, 0, sizeof(buf));
snprintf (buf, sizeof(buf)-1, "%llu", (unsigned long long) trackuid);
func(buf);

should work when sizeof(unsigned long long) == sizeof(uint64_t)sizeof(unsigned long long) == sizeof(uint64_t)时应该工作

EDIT编辑

but the better answer is by Maxim Yegorushkin to use "%"PRIu64但更好的答案是 Maxim Yegorushkin 使用"%"PRIu64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM