Need help understanding code

Started by mr_kanister, August 05, 2013, 09:46:37 AM

Previous topic - Next topic

mr_kanister

I've got a source file, but can't understand one line, i would be pleased if someone could explain me what exactly is happening here:

int field = *(DWORD *)(packet + 0x08);

As far as i understood the code, packet is an array of bytes, which is filled with the data read by fpacket.
both are initilaized like this:

BYTE* packet = NULL;
FILE *fpacket;


Here is where the bytes are written into packet:

packet = malloc(filesize+1);
memset(packet, 0, filesize+1);
fread(packet, filesize, 1, fpacket);


Thank you in advance

frankie

#1
The line simply reads *edit* 4 bytes together (DWORD is 4 bytes) displaced of 8 bytes from beginning of the array. Is enough?  8)
OK let get a little deeper.
'packet ' is a pointer to a BYTE array.
packet + 0x08
points to 8 bytes forward (the eigthth byte from array begin)
(DWORD *)
This is a 'casting'. Crafted this way we are saying to compiler to consider the previous variable (packet + 0x08) no more a byte pointer, but a DWORD pointer.
The last asterisk, the first before assignment, tells to the compiler to get the DWORD value pointed by the pointer (and then assigning it to the variable 'field'.
int field = [Get the DWORD pointed to]*[convert it to DWORD pointer](DWORD *)([displace 'packet pointer of 8 bytes] packet + 0x08);
Hope is clear enough.....
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide

mr_kanister

That helped me a lot.

Thank you for your help  :D

frankie

#3
You're welcome.
I edited the former post because of a mistake on DWORD size (a DWORD is 4 bytes long).
I can also add that the code:
int field = *(DWORD *)(packet + 0x08);
have one more intrinsic casting from DWORD to int.
It would have been better:
int field = *(int *)(packet + 0x08);
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide