Question

Let's say I have some structs similar to this:

struct a {
    uint8_t v1[6];
    uint16_t type;
    uint8_t v2[6];
    uint32_t something_long;
};

struct b {
    uint8_t v3;
    uint8_t v4;
};

struct c{
    a a;
    b b;
}

and I fill data like (is this correct?):

int main() {...

    c my_struct;

    my_struct.a.v1[0] = 0x01;
    my_struct.a.v1[1] = 0x02;
    .
    .
    .

    my_struct.a.type = 2048; // <- does this integer convert to "hex"?

Now what I am trying to achieve is get my_struct and be able to make u_char buff from my_struct

u_char buff[sizeOf(c)]; 

someConversionStuffHere(c, buff);
//function returns data like:
    //buff[0] = 0x01; //wanted result
    //buff[1] = 0x02; //wanted result

so I can take buff and use it in 3rd party library that requires u_char as parameter.

I've tried some crazy things like:

looping in while and using sscanf(), I mean I can print out c in hex using:

u_char *string_ptr = (U_char *)&p;
int i = sizeof(c);

while(i--) {
    u_char c = *string_ptr++;
    printf(" %x ", (u_char) c);
}

This prints "correctly" values uint8_t v1[6] and uint8_t v2[6], but when I try to print out 2048 as hex (it should be 0x800) it prints out 0 8 instead (not 08 00 as I would expect).

I would love debug this but C/C++ isn't PHP where I can primitively print out anything without problem.

Was it helpful?

Solution

Yes, what @Mats said is correct: this is because of endianness.. You can see an illustration of what's going on "under the covers" on the Wikipedia page: http://en.m.wikipedia.org/wiki/Endian

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top