简体   繁体   中英

Why is <inttypes.h>'s PRIx16 not equal to “hx”?

Why is PRIx16 == "x" in C (and in C++ ) under GCC?

I would expect it to be "hx" , so that the following works:

#include <inttypes.h>

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

Short answer:

To print signed types use d , i .

To print unsigned types, use x , u , o .


int16_t v is a signed integer type.

PRIxN as in PRIx16 is listed as a "fprintf macros for unsigned integers". PRIxN is not listed for "fprintf macros for signed integers". @Kerrek SB

To print v , as decimal text, use PRId16 or PRIi16 .

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

To print v as a hexadecimal text, cast/convert to some unsigned.

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

I also would expect "hx" for PRIx16 and that is the way with my GCC compilation (GNU C11 (GCC) version 6.4.0) yet this is more likely a standard library version issue (mine: ldd (cygwin) 2.9.0). I have doubts about the up-to-date-ness of OP's compiler/library.

#include <stdio.h>
#include <inttypes.h>

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

Output

hx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM