预处理器部门提供奇怪的价值
Preprocessor division giving weird value
这让我发疯。我有一个代码在使用除法时输出了一个奇怪的值:
#define NANOSECONDS_PER_SECOND 1000000000
uint64 CurrentTimeInNanoSecs;
uint64 GetTimeInNanoSecs( )
{
printf("\n%X", (CurrentTimeInNanoSecs >> 32) );
printf("\n%X", (CurrentTimeInNanoSecs & 0xFFFFFFFF) );
return ( CurrentTimeInNanoSecs );
}
void GetCurrentTimeInSecs()
{
uint32 Time = GetTimeInNanoSecs() / NANOSECONDS_PER_SECOND;
printf("%X", time);
}
void main()
{
GetCurrentTimeInSecs();
}
在初始化时,我看到打印如下:
0x00000000
0x3016DC6B
0x00000198
我不确定发生了什么。有人可以帮忙吗
注意 printf 格式说明符必须与传递的数据类型一致,否则数据可能会被误解并打印为乱码!
打印 uint64_t 的正确方法是使用 printf("%" PRIu64 "\n", x);
,其中 PRIu64 在 inttypes.h. Note: Pre-C11, you may need to define __STDC_FORMAT_MACROS to get PRIu64, as described in this SO post.
中定义
更一般地说,请参阅维基百科上 https://en.cppreference.com/w/cpp/io/c/fprintf of the expected types for each specifier. There's also a good printf format string 文章中关于它的 table。
我建议在打开警告的情况下进行编译。如果使用 clang 或 gcc,请使用命令行选项 -Wall
。大多数编译器应该对发布的代码发出警告,例如:
format '%X' expects argument of type 'unsigned int', but argument has type 'uint64_t'
我的缺点:
我知道我将代码发布为:
printf("\n%X", (CurrentTimeInNanoSecs >> 32) );
但实际上我是这样写的:
printf("\n%X", (CurrentTimeInNanoSecs & 0xFFFFFFFF >> 32) );
所以我的高 32 位总是零,我误解了结果:/
感谢社区。
这让我发疯。我有一个代码在使用除法时输出了一个奇怪的值:
#define NANOSECONDS_PER_SECOND 1000000000
uint64 CurrentTimeInNanoSecs;
uint64 GetTimeInNanoSecs( )
{
printf("\n%X", (CurrentTimeInNanoSecs >> 32) );
printf("\n%X", (CurrentTimeInNanoSecs & 0xFFFFFFFF) );
return ( CurrentTimeInNanoSecs );
}
void GetCurrentTimeInSecs()
{
uint32 Time = GetTimeInNanoSecs() / NANOSECONDS_PER_SECOND;
printf("%X", time);
}
void main()
{
GetCurrentTimeInSecs();
}
在初始化时,我看到打印如下: 0x00000000 0x3016DC6B 0x00000198
我不确定发生了什么。有人可以帮忙吗
注意 printf 格式说明符必须与传递的数据类型一致,否则数据可能会被误解并打印为乱码!
打印 uint64_t 的正确方法是使用 printf("%" PRIu64 "\n", x);
,其中 PRIu64 在 inttypes.h. Note: Pre-C11, you may need to define __STDC_FORMAT_MACROS to get PRIu64, as described in this SO post.
更一般地说,请参阅维基百科上 https://en.cppreference.com/w/cpp/io/c/fprintf of the expected types for each specifier. There's also a good printf format string 文章中关于它的 table。
我建议在打开警告的情况下进行编译。如果使用 clang 或 gcc,请使用命令行选项 -Wall
。大多数编译器应该对发布的代码发出警告,例如:
format '%X' expects argument of type 'unsigned int', but argument has type 'uint64_t'
我的缺点: 我知道我将代码发布为:
printf("\n%X", (CurrentTimeInNanoSecs >> 32) );
但实际上我是这样写的:
printf("\n%X", (CurrentTimeInNanoSecs & 0xFFFFFFFF >> 32) );
所以我的高 32 位总是零,我误解了结果:/
感谢社区。