when to use hton/ntoh and when to convert data myself?

杀马特。学长 韩版系。学妹 提交于 2019-12-18 09:04:23

问题


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?


回答1:


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.




回答2:


Through the network you always receive a series of bytes (octets), which you can't directly pass to ntohs or ntohl. Supposing the incoming bytes are buffered in the (unsigned) char array buf, you could do short x = ntohs(*(short *)(buf+offset)); but this is not portable unless buf+offset is always even, so that you read with correct alignment. Similarly, to do long y = ntohl(*(long *)(buf+offset)); you have to make sure that 4 divides buf+offset. Your convert() functions, though, don't have this limitation, they can process byte series at arbitrary (unaligned) memory address.



来源:https://stackoverflow.com/questions/21996794/when-to-use-hton-ntoh-and-when-to-convert-data-myself

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!