Monday, May 21, 2012

Putting 4 bytes on the location in the buf


#include <stdio.h>
#include <string.h>

// Experiment (Linux)
// Putting 4 bytes on the location in the buf
// Getting 4 bytes from the char buf to uint32

#define DATA32 0x1234abcd;
int main(void) {
    char *ptr;
    char buf[16];
    int i;
    unsigned int value;

    memset((char *)buf, 0, 16);
    ptr = buf;

    // put
    *(unsigned int *) ptr = DATA32;

    printf("*ptr     = 0x%x\n", *ptr);
    printf("*(ptr+1) = 0x%x\n", *(ptr+1));
    printf("*(ptr+2) = 0x%x\n", *(ptr+2));
    printf("*(ptr+3) = 0x%x\n", *(ptr+3));


    for(i=0; i<16; i++) {
        printf("buf[%d]: 0x%x\n", i, buf[i]);
    }

    // get
    value = *(unsigned int *) ptr;

    printf("value = 0x%x\n", value);



    return 0;
}

/*****************************
Output
#[600]a.out
*ptr     = 0xffffffcd
*(ptr+1) = 0xffffffab
*(ptr+2) = 0x34
*(ptr+3) = 0x12
buf[0]: 0xffffffcd
buf[1]: 0xffffffab
buf[2]: 0x34
buf[3]: 0x12
buf[4]: 0x0
buf[5]: 0x0
buf[6]: 0x0
buf[7]: 0x0
buf[8]: 0x0
buf[9]: 0x0
buf[10]: 0x0
buf[11]: 0x0
buf[12]: 0x0
buf[13]: 0x0
buf[14]: 0x0
buf[15]: 0x0
value = 0x1234abcd
******************************/

No comments:

Post a Comment