简体   繁体   English

Solaris 9上的printf + uint_64?

[英]printf + uint_64 on Solaris 9?

I have some c(++) code that uses sprintf to convert a uint_64 to a string. 我有一些c(++)代码使用sprintf将uint_64转换为字符串。 This needs to be portable to both linux and Solaris. 这需要可移植到Linux和Solaris。

On linux we use %ju, but there does not appear to be any equivalent on Solaris. 在linux上我们使用%ju,但在Solaris上似乎没有任何等价物。 The closest I can find is %lu, but this produces incorrect output. 我能找到的最接近的是%lu,但这会产生不正确的输出。 Some sample code: 一些示例代码:

#include <stdio.h>
#include <sys/types.h>

#ifdef SunOS
typedef uint64_t u_int64_t;
#endif

int main(int argc, char **argv) {
    u_int64_t val = 123456789123L;

#ifdef SunOS
    printf("%lu\n", val);
#else
    printf("%ju\n", val);
#endif
}

On linux, the output is as expected; 在linux上,输出是预期的; on Solaris 9 (don't ask), it's "28" 在Solaris 9上(不要问),它是“28”

What can I use? 我可以用什么?

If you have have inttypes.h available you can use the macros it provides: 如果你有inttypes.h可用,你可以使用它提供的宏:

printf(  "%" PRIu64 "\n", val);

Not pretty (I seem to be saying that a lot recently), but it works. 不漂亮(我最近似乎说了很多),但它确实有效。

On a C99 compliant system: 在符合C99的系统上:

#include <inttypes.h>

uint64_t big = ...;
printf("%" PRIu64 "\n", big);

See section 7.8 of the C99 standard. 见C99标准第7.8节。

The specifiers are {PRI,SCN}[diouxX]{N,LEASTN,MAX,FASTN,PTR} 说明符是{PRI,SCN} [diouxX] {N,LEASTN,MAX,FASTN,PTR}

Where PRI is for the printf() family, SCN is for the scanf() family, d and i for signed integral types; PRI用于printf()系列,SCN用于scanf()系列,d和i用于有符号整数类型; o,u,x,X are for unsigned integral types as octal, decimal, hex, and Hex; o,u,x,X用于无符号整数类型,如八进制,十进制,十六进制和十六进制; N is one of the supported widths; N是支持的宽度之一; LEAST and FAST correspond to those modifiers; LEAST和FAST对应于那些修饰符; PTR is for intptr_t; PTR用于intptr_t; and MAX is for intmax_t. 和MAX用于intmax_t。

The answer depends on whether your code is actually C or C++. 答案取决于您的代码实际上是C还是C ++。 In C, you should be using an unsigned long long rather than another type (this is conformant to the current standard, and long long is pretty common as far as C99 support goes), appending ULL instead of L to your constant, and using (as has been mentioned) %llu as your specifier. 在C中,你应该使用unsigned long long而不是其他类型(这符合当前标准,并且就C99支持而言long long很常见),将ULL而不是L附加到常量,并使用(正如已经提到的那样) %llu作为你的说明者。 If support for C99 doesn't exist, you may want to check the compiler documentation, as there is no other standard way to do it. 如果不存在对C99的支持,您可能需要检查编译器文档,因为没有其他标准方法可以执行此操作。 long long is guarateed to be 64 bits at least. long long至少被保证为64位。

You can use %llu for long long. 你可以长时间使用%llu However, this is not very portable either, because long long isn't guaranteed to be 64 bits. 但是,这也不是非常便携,因为long long不能保证是64位。 :-) :-)

如果要避免使用SunOS条件typedef,可以从stdint.h获取uint64_t

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

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