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

前端 未结 2 1969
逝去的感伤
逝去的感伤 2020-12-21 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( in         


        
2条回答
  •  一生所求
    2020-12-21 05:10

    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.

提交回复
热议问题