-1

I had expected each memory address contain 1-byte data. But on below code, I getting 4-byte hex value. Why this happened?

I'm aware of negative int representation.

char num = -25;
char *ptr = #
printf("%02X", *ptr);

Output : FFFF FFE7

Expected : E7

Edit : Another good answer in here : https://stackoverflow.com/a/8060195/17823490

logico
  • 43
  • 1
  • 6
  • If `I'm aware of negative int representation.` why are you asking the question? `*ptr` is being converted to a 4-byte `int`. If you don't want this, do this: `printf("%02X", (uint8_t)*ptr);`. – Fiddling Bits Aug 13 '23 at 23:51
  • 1
    %X prints unsigned int as a hexadecimal number. x uses lower-case letters and X uses upper-case. – Jarod42 Aug 13 '23 at 23:51
  • @EtiennedeMartel: with C-variadic ellipsis, there are some convertions happening. see [cppreference](https://en.cppreference.com/w/cpp/language/variadic_arguments#Default_conversions) for details – Jarod42 Aug 13 '23 at 23:54
  • @EtiennedeMartel it gets promoted to an int iirc. – Shawn Aug 13 '23 at 23:54
  • Ah, right. I hate C variadics. – Etienne de Martel Aug 13 '23 at 23:54
  • @EtiennedeMartel no, there is no UB. char is being converted to int as it as variadic function – 0___________ Aug 13 '23 at 23:55
  • 2
    You shouldn't make assumptions about the signedness of `char`. That is implementation-defined. `char` is a distinct type, separate from `signed char` and `unsigned char`, unlike other integral types that are implicitly signed. – paddy Aug 13 '23 at 23:59
  • @paddy it does not matter in this case https://godbolt.org/z/vn5YYzajE as if it is unsigned the program will behave exactly the same – 0___________ Aug 14 '23 at 00:10

1 Answers1

5
printf("%02X", *ptr);

*ptr is being converted to int and printed as int

You need to use the correct printf format:

printf("%02hhX", *ptr);
0___________
  • 60,014
  • 4
  • 34
  • 74