Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c - how to read memory bytes one by one in hex(so without any format) with printf()

I'm interested to read one byte of memory in C.Im using netbeans on ubuntu and below is my code to read just one byte(not the whole value of a). but nothing is printed out on the screen.

main()
{
int a[1]={3};
//printf(%d",a[0]); //line 2
printf("x07",a[0]); //line 3
}

in my idea, the memory in address with label a is composed of:

  • 0x0004 03
  • 0x0008 00
  • 0x000c 00
  • 0x000f 00

printf() statement in line 2 indicates that go to the address 0x???4 and :

  1. read 4 bytes (because of d character)
  2. Represent these 4 bytes as a number meaning that multiply them by power of 2 (because of d character)

printf() statement in line 3 use (and not %) and bits from 0 to 7 (1 byte). so it indicates that, go address 0x0004 and:

  1. List item
  2. read 1 byte (because of 07 characters) 2-Do nothing except that show each 4-bit as a hex value

so the code should print out what the first byte in 0x0004 which is 03. but it does not. any clue?

Thanks in advance

Please don't just correct my syntax. Do you think my hypotheses are correct regarding formatters in printf?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a pointer to address the individual bytes of a and change your printf to use the %x format specifier, e.g.:

int main(void)
{
    int a = 3;
    unsigned char *p = (unsigned char *)&a;
    int i;

    printf("a =");
    for (i = 0; i < sizeof(a); ++i)
    {
        printf(" %02x", p[i]);
    }
    printf("
");
    return 0;
}

On a little endian machine with 32 bit ints this should produce the following output:

a = 03 00 00 00

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...