从 unsigned char * 到 unsigned int 的 memcpy
memcpy from unsigned char * to unsigned int
我不确定以下 C++ 代码的作用(我已经用点替换了无关紧要的部分):
unsigned char* p = ...;
unsigned int metaNum;
memcpy( &metaNum, p, sizeof( unsigned int ) );
p += sizeof( unsigned int );
for ( unsigned int m = 0; m < metaNum; m++ ) {
...
}
我知道memcpy
:
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.
我仍然不确定 metaNum
的解释是什么。它是显而易见的还是与实施有关?
这不是特定于实现的:metaNum
被解释为 sizeof(unsigned int)
字节的序列,p
指向的相同字节数的内容被复制到其中.
这里唯一起作用的是 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
将字节序列调整为正确顺序的函数。
我不确定以下 C++ 代码的作用(我已经用点替换了无关紧要的部分):
unsigned char* p = ...;
unsigned int metaNum;
memcpy( &metaNum, p, sizeof( unsigned int ) );
p += sizeof( unsigned int );
for ( unsigned int m = 0; m < metaNum; m++ ) {
...
}
我知道memcpy
:
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.
我仍然不确定 metaNum
的解释是什么。它是显而易见的还是与实施有关?
这不是特定于实现的:metaNum
被解释为 sizeof(unsigned int)
字节的序列,p
指向的相同字节数的内容被复制到其中.
这里唯一起作用的是 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
将字节序列调整为正确顺序的函数。