1、使用 PRIi64 格式控制符
在 C99 标准中,stdint.h
提供了特定的宏来打印 int64_t
类型的变量。使用 PRIi64
宏来确保代码的可移植性。
#include <stdio.h>
#include <stdint.h>
int main() {
int64_t num = 1234567890123456789;
printf("The number is: %" PRIi64 "\n", num);
return 0;
}
2、宏定义来源
在 inttypes.h
中,PRIi64
是针对不同平台上 64 位整数的标准化格式控制符,定义为#define PRIi64 "lld" PRIi64
宏会为 int64_t
类型提供一个适当的格式控制符,确保在各种平台上的兼容性。
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h> // 引入 inttypes.h 来使用 PRIi64
int main() {
int64_t num = 1234567890123456789;
printf("The number is: %" PRIi64 "\n", num);
return 0;
}
3、int64_t 的其他常用宏
除了 PRIi64
,inttypes.h
还为其他类型提供了宏,PRId64
打印 int64_t
类型的值(十进制)。PRIu64
打印 uint64_t
类型的值(无符号十进制)。PRIx64
打印 int64_t
类型的值(十六进制,小写)。PRIX64
打印 int64_t
类型的值(十六进制,大写)。
1)处理时间戳或日期
int64_t
可以用来表示时间戳,尤其是在处理毫秒级或纳秒级精度的时间时。如可以用 int64_t
存储自纪元以来的毫秒数。
#include <stdio.h>
#include <inttypes.h>
#include <time.h>
int main() {
// 获取当前时间戳(单位为秒)
int64_t timestamp = (int64_t)time(NULL);
printf("Current timestamp is: %" PRIi64 "\n", timestamp);
return 0;
}
2)大数计算
当需要进行高精度的整数运算(如财务计算、大型数据计算)时,int64_t
是一个理想的选择。如处理某些加法或乘法运算时,结果可能会超出 int
的范围,因此 int64_t
提供了更大的存储空间。
#include <stdio.h>
#include <inttypes.h>
int main() {
int64_t large_num1 = 9223372036854775807; // 最大值
int64_t large_num2 = 1000;
int64_t result = large_num1 + large_num2;
printf("Large number sum: %" PRIi64 "\n", result);
return 0;
}
3)文件大小计算
在处理文件大小时,尤其是大文件时,int64_t
是一个合适的选择。
#include <stdio.h>
#include <inttypes.h>
#include <sys/stat.h>
int main() {
struct stat file_stat;
if (stat("example_file.txt", &file_stat) == 0) {
int64_t file_size = file_stat.st_size;
printf("File size is: %" PRIi64 " bytes\n", file_size);
} else {
perror("File not found");
}
return 0;
}