NO

Author Topic: Need help understanding code  (Read 2489 times)

mr_kanister

  • Guest
Need help understanding code
« on: August 05, 2013, 09:46:37 AM »
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:

Code: [Select]
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:

Code: [Select]
BYTE* packet = NULL;
FILE *fpacket;

Here is where the bytes are written into packet:

Code: [Select]
packet = malloc(filesize+1);
memset(packet, 0, filesize+1);
fread(packet, filesize, 1, fpacket);

Thank you in advance

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2113
Re: Need help understanding code
« Reply #1 on: August 05, 2013, 03:42:32 PM »
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.
Code: [Select]
packet + 0x08points to 8 bytes forward (the eigthth byte from array begin)
Code: [Select]
(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'.
Code: [Select]
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.....
« Last Edit: August 05, 2013, 04:18:49 PM by frankie »
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide

mr_kanister

  • Guest
Re: Need help understanding code
« Reply #2 on: August 05, 2013, 03:57:05 PM »
That helped me a lot.

Thank you for your help  :D

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2113
Re: Need help understanding code
« Reply #3 on: August 05, 2013, 04:20:06 PM »
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:
Code: [Select]
int field = *(DWORD *)(packet + 0x08);have one more intrinsic casting from DWORD to int.
It would have been better:
Code: [Select]
int field = *(int *)(packet + 0x08);
« Last Edit: August 05, 2013, 04:23:31 PM by frankie »
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide