Char * (array) discarded in unsigned long + 1?

I am trying to port some C code to Java, however I was struggling to figure out what these lines of code do.

Note: rawEntryis of type char*and is likely to be 12 bytes 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 elements of the array and puts them together to form a long one, however my attempts in java were less successful.

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

When the following array is presented,

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

C code outputs 3034 as offset My Java code outputs 16777217 or 1 if I flip endian

+4
source share
2 answers

This expression

l = (unsigned long*) rawEntry + 1;

casts rawEntry, , 8 . 1 8 , :

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

3034:

0 0 11 -38

, ByteBuffer:

int offset = ByteBuffer.wrap(rawEntry, 8, 4).getInt();
+5

, , a long . 64- longs 64 , long 8 . , ntohl " " 32 (4 ).

, rawEntry {1,0,0,0,0,0,0,0,0,0,0xB,0xDA,…} (0xB 16 11, 0xDA 16 () unsigned, -38)

l = (unsigned long*) rawEntry + 1;

, l unsigned long. 8 rawEntry l, {0,0,0xB,0xDA,…}. *l unsigned long, {0,0,0xB,0xDA,…}, . , 0x... DA0B0000 (, , undefined). ntohl 32 , 0x00000BDA 3034 10.

Java

offset = (rawEntry[8] << 24) +
         (rawEntry[9] << 16) +
         (rawEntry[10] << 8) +
         (rawEntry[11]);
+2

Source: https://habr.com/ru/post/1661985/


All Articles