-2

I am not sure what the following C++ code does (I have replaced parts that don't matter with dots):

unsigned char* p = ...;
unsigned int metaNum;
memcpy( &metaNum, p, sizeof( unsigned int ) );
p += sizeof( unsigned int );

for ( unsigned int m = 0; m < metaNum; m++ ) {

...

}

I know for memcpy that:

The underlying type of the objects pointed to by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.

Still I am not sure what is the interpretation of metaNum. Is it something obvious or it has to do with the implementation?

Stargateur
  • 24,473
  • 8
  • 65
  • 91
mgus
  • 808
  • 4
  • 17
  • 39

1 Answers1

2

This is not implementation-specific: metaNum is interpreted as a sequence of sizeof(unsigned int) bytes, into which the content from the same number of bytes pointed to by p is copied.

The only thing in play here is endianness: the same sequence of bytes copied into metaNum will be interpreted differently depending on how the hardware is storing multi-byte values, such as unsigned int. If the sequence comes from the same hardware, interpretation would be the same. Otherwise, you would need to use ntoh/hton functions to bring byte sequences into proper order.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523