-1

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?

4

3 回答 3

6

使用指针来寻址各个字节a并更改您的printf以使用%x格式说明符,例如:

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("\n");
    return 0;
}

在具有 32 位整数的小端机器上,这应该产生以下输出:

a = 03 00 00 00
于 2013-08-16T12:20:42.823 回答
0
main()
{
    int a = 3; // you can use any type you need.
    size_t size = sizeof(a);
    char *phead = malloc(size);
    memcpy(phead,&a,size);
    size_t i;
    char *p = phead;
    for(i = 0; i < size; i++)
        printf("%02x  ",*p++);
    free( phead); 
}
于 2013-08-16T13:38:22.353 回答
-1

printf 有一个十六进制格式化程序。它是“%x”...

$ man 3 printf

与上面相同,但适用于 64 位整数。

#include <stdio.h>
#include <sys/types.h>

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

    printf("a = 0x");

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

    printf("\n");

    return 0;
}
于 2013-08-16T12:17:18.637 回答