2

I have a simple question. The code is really short so I just post it here

#include <stdio.h>
int main(int argc, const char * argv[])
{

    long int p;

    printf("FYI: address of first local varaible of main() on the function stack:%p\n",&p);
    printf("Enter start address <hex notation> of dump:");
    scanf("%lx",&p);

    char * q;
    q = (char*)p;

    printf("%x\n",*q);

    return 0;
}

The result of last printf, for example is ffffffc8. What if I only want to keep the last two: c8. How can I do that? I tried: printf("%2x",*q); and printf("%x",*q % 256); But neither works. Can some one help? Thanks!

lancellx
  • 285
  • 1
  • 5
  • 15
  • There may be a more root-cause answer over at http://stackoverflow.com/questions/30463962/printf-char-as-hex-in-c/30464318#30464318 -- specifically, you need to cast the value as an unsigned int or add the 'hh' specifier to limit the size to char (per http://www.cplusplus.com/reference/cstdio/printf/) – Rob Fagen May 26 '15 at 16:45

2 Answers2

7

To print the least-significant byte of *q in hex you could use:

printf("%02x", *q & 0xFF);

This of course assumes that q can be dereferenced.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Thank you that works. But I want to use a for loop to this printf for more than one address. like printf("%2x",*(q++) & 0xFF); Sometimes the in the memory it is empty, the result is 0. Is there a way to make it also 00. So I can make the print result very tidy.(Two number in every result). – lancellx Mar 08 '13 at 14:31
  • @lancellx: The code in my current answer already does that (the format is `"%02x"` -- note the `0`). – NPE Mar 08 '13 at 14:31
0

First convert to unsigned:

unsigned char q = *(unsigned char *)(p);
printf("%02X", q);

(Otherwise, if your char is signed, the variadic default promotion converts the value to int, and the result may be negative.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • I did't try you answer because I have to use pointer.(School assignment..) Thank you all the same. – lancellx Mar 08 '13 at 14:33
  • @User1: Hm, I see. A matter of debate, I suppose, whether the OP means the "last two" character of the binary representation of the integer, or the remainder modulo 256 of the integer. She should just read into a `uintptr_t` and print `p % 0x100` in that case, I suppose. – Kerrek SB Mar 08 '13 at 14:33