为什么的PRIx16不等于“hx”?

为什么在GCC下的C (和C ++ )中PRIx16 == "x"

我希望它是"hx" ,以便以下工作:

 #include  int16_t v = -1; printf("%04" PRIx16 "\n", v); // prints ffffffff, not ffff 

简短回答:

要打印签名类型,请使用di

要打印无符号类型,请使用xuo


int16_t v是有符号整数类型。

PRIxN中的PRIx16被列为“无符号整数的fprintf宏”。 PRIxN未列为“用于签名整数的fprintf宏”。 @Kerrek SB

要以小数文本forms打印v ,请使用PRId16PRIi16

 printf("%04" PRId16 "\n", v); 

要将v作为hex文本打印,请转换/转换为某些无符号文本。

 printf("%04" PRIx16 "\n", (uint16_t)v); 

我也期望PRIx16 "hx" ,这是我的GCC编译方式(GNU C11(GCC)版本6.4.0)但这更可能是标准的库版本问题(我的:ldd(cygwin)2.9.0) 。 我对OP的编译器/库的最新版本有疑问。

 #include  #include  int main(void) { printf(PRIx16); return 0; } 

产量

 hx