Search code examples
c#ccode-translation

Understanding a C function for C# translation


I am side-checking some code that was translated from C to C#. I have a question on the original C:

...
#define getblock(p, i) (p[i])
...
void MurmurHash3_x86_32 ( const void * key, int len,
                          uint32_t seed, void * out )
{
  const uint8_t * data = (const uint8_t*)key;
  const int nblocks = len / 4;
  int i;

  uint32_t h1 = seed;

  uint32_t c1 = 0xcc9e2d51;
  uint32_t c2 = 0x1b873593;

  const uint32_t * blocks = (const uint32_t *)(data + nblocks*4);

  for(i = -nblocks; i; i++)
  {
    uint32_t k1 = getblock(blocks,i);
...

The part for(i = -nblocks; i; i++) ... is this looping through the data backwards? I've never seen data referred to with a negative index.


Solution

  • No it's not looping through the data backwards. It starts at the beginning of data, and indexes up.

    As you can see, here the pointer "blocks" is advanced past "data" already. It points "nblocks" past the beginning of data.

    const uint32_t * blocks = (const uint32_t *)(data + nblocks*4);
    

    So, you need a negative index to get to the beginning of data (-nblocks). The start of data is precisely at "blocks[-nblocks]". The "for" loop simply starts there, and counts up.

    for(i = -nblocks; i; i++)