预处理程序划分提供了奇怪的价值

问题描述

这让我发疯。我有一个使用除法时输出怪异值的代码:

#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中定义。注意:在C11之前,您可能需要定义__STDC_FORMAT_MACROS才能获得PRIu64,如in this SO post所述。

通常,请参见https://en.cppreference.com/w/cpp/io/c/fprintf中每个说明符的预期类型表。维基百科上也有一篇不错的printf format string文章。

我建议在打开警告的情况下进行编译。如果使用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位始终为零,并且我误解了结果:/

不过,谢谢您的社区。​​ p>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...