何时使用hton / ntoh以及何时自己转换数据? [英] when to use hton/ntoh and when to convert data myself?
问题描述
要从另一台big-endian机器转换字节数组,我们可以使用:
long long convert(unsigned char data []){
long long res;
res = 0;
for(int i = 0; i< DATA_SIZE; ++ i)
res =(res<< <8)+ data [i];
美元的回报;
}
如果另一台计算机是低位优先的,我们可以使用
long long convert(unsigned char data []){
long long res;
res = 0;
for(int i = DATA_SIZE-1; i> = 0; --i)
res =(res< <8)+ data [i];
美元的回报;
}
为什么需要上述功能?我们不应该在发件人处使用hton并在接收时使用ntoh吗?
<$ c $是不是因为hton / nton会在此convert()用于char数组时转换整数?
hton
/ ntoh
函数在网络顺序和主机顺序之间进行转换。如果这两个相同(即在大端机器上),则这些功能无效。因此,不能轻而易举地依靠它们来交换字节序。另外,正如您所指出的,它们仅针对16位( htons
)和32位( htonl
)整数;您的代码最多可以处理 sizeof(long long)
,具体取决于 DATA_SIZE
的设置方式。
to convert a byte array from another machine which is big-endian, we can use:
long long convert(unsigned char data[]) {
long long res;
res = 0;
for( int i=0;i < DATA_SIZE; ++i)
res = (res << 8) + data[i];
return res;
}
if another machine is little-endian, we can use
long long convert(unsigned char data[]) {
long long res;
res = 0;
for( int i=DATA_SIZE-1;i >=0 ; --i)
res = (res << 8) + data[i];
return res;
}
why do we need the above functions? shouldn't we use hton at sender and ntoh when receiving? Is it because hton/nton is to convert integer while this convert() is for char array?
The hton
/ntoh
functions convert between network order and host order. If these two are the same (i.e., on big-endian machines) these functions do nothing. So they cannot be portably relied upon to swap endianness. Also, as you pointed out, they are only defined for 16-bit (htons
) and 32-bit (htonl
) integers; your code can handle up to the sizeof(long long)
depending on how DATA_SIZE
is set.
这篇关于何时使用hton / ntoh以及何时自己转换数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!