0

enter image description here

i thought *(p3 + 3) will print 90 but it shows ffffff90 why does it happend? i guess MSB is 1, and %x is for reading unsinged hexadecimal integer so it reads 90 like minus integer but it is not clear and i cant find about this problem at printf reference https://cplusplus.com/reference/cstdio/printf/ is there anyone who explain this?

as df
  • 29
  • 6
  • 3
    Welcome to Stack Overflow. Please simplify your program down to a [mcve] and post the entire program and its output as text, not an image. You have lots of unneeded variables and print commands. – David Grayson Jun 27 '22 at 04:58
  • @DavidGrayson im sorry i'll try it – as df Jun 27 '22 at 05:07
  • 1
    In the future, please post text as text, not just as a screenshot. – ikegami Jun 27 '22 at 05:16
  • [Why should I not upload images of code/data/errors when asking a question?](https://meta.stackoverflow.com/q/285551/995714) – phuclv Jun 27 '22 at 08:16

1 Answers1

2

Use an unsigned char *.


In your environment,

  • char is signed.
  • char is 8 bits.
  • Signed numbers use two's complement.

So you have a char with a bit pattern of 9016. In this environment, that's -112. So you are effectively doing the following:

printf( "%x", (char)-112 );

When passing to variadric function like printf, the smaller integer types are implicitly promoted to int or unsigned int. So what's really happening is this:

printf( "%x", (int)(char)-112 );

So you're passing the int value -112. On your machine, that has the bit pattern FF FF FF 9016 (in some unknown byte order). %x expects an unsigned integer, and thus prints that bit pattern as-is.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • If your platform (C library) supports it, you can print using `printf("%hhx\n", -112)` and the output will be 90 as desired. See the POSIX specification for [`printf()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html) or the C standard (C11) specification for [§7.21.6.1 The `printf` function](http://port70.net/~nsz/c/c11/n1570.html#7.21.6.1). – Jonathan Leffler Jun 27 '22 at 05:36
  • @Jonathan Leffler, I was aware of that, but I don't like that hack. `%x` requires an unsigned number, and there's no reason to use the wrong type and try to fix it up afterwards. – ikegami Jun 27 '22 at 06:09