当前位置:网站首页>The solution of outputting 64 bits from printf format%lld of cross platform (32bit and 64bit)

The solution of outputting 64 bits from printf format%lld of cross platform (32bit and 64bit)

2022-07-05 11:54:00 Big orange madness

Problem description

stay C/C++ In development , Use printf Print 64 Bit variables are commonly used , Usually in 32 Bit system %lld Output 64 Bit variables , And in the 64 In the bit system %ld;

If in 32 Bit system %ld Output 64 Bit variable , It is likely that the printed value is abnormal , And in the 64 In the bit system %lld, Compilation errors usually occur , Similar to :

format '%lld' expects type 'long long int', but argument 4 has type 'int64_t'[ -Werror=format=]

If you migrate code across platforms , This is usually the case .


Solution

In order to solve the problem of cross platform migration ,% PRId64 The way of writing solves the problem of cross platform , Mainly to support 32 Bit and 64 Bit operating system .PRId64 Express 64 An integer , stay 32 Bit system long long int, stay 64 Bit system long int.

Writing format :

uint64_t value = 1560;
printf("value = %" PRId64 "\n", value);

The effect is as follows :

uint64_t value = 1560;
printf("value = %" "%ld" "\n", value);   // 64bit OS
printf("value = %" "%lld" "\n", value);  // 32bit OS

perhaps

uint64_t value = 1560;
printf("value = %ld\n", value);   // 64bit OS
printf("value = %lld\n", value);  // 32bit OS

原网站

版权声明
本文为[Big orange madness]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051140365774.html