CraftedCart CraftedCart - 12 days ago 8
C Question

char* (Array) cast to unsigned long + 1?

I'm trying to port some C code to Java, however I've been struggling to figure out what these lines of code do.

Note:

rawEntry
is of type
char*
and appears to be a 12 bytes long allocated as such

char *rawEntry = (char*)malloc(0x000c);





unsigned long *l;
unsigned long offset;

// ...

l = (unsigned long*) rawEntry + 1;
offset = ntohl(*l);


As far as I can tell, it takes the first four items of the array, and puts them together to form a long, however my attempts in java have been less than successful.

offset = (rawEntry[0] << 24) +
(rawEntry[1] << 16) +
(rawEntry[2] << 8) +
(rawEntry[3]) +
1;


When presented with the following array,

1 0 0 0 0 0 0 0 0 0 11 -38


The C code outputs 3034 as the offset

My Java code outputs 16777217, or 1 if I flip the endian

Answer

This expression

l = (unsigned long*) rawEntry + 1;

casts rawEntry to pointer to a type that has size of 8 bytes on your system. After that, adding 1 means adding 8 bytes, so the actual conversion looks like this:

offset = (Byte.toUnsignedInt(rawEntry[ 8]) << 24) +
         (Byte.toUnsignedInt(rawEntry[ 9]) << 16) +
         (Byte.toUnsignedInt(rawEntry[10]) <<  8) +
         (Byte.toUnsignedInt(rawEntry[11]) <<  0);

The following four bytes are interpreted as 3034:

0 0 11 -38