Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

endianness

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?

like image 210
user389955 Avatar asked Mar 21 '23 11:03

user389955


1 Answers

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.

like image 168
TypeIA Avatar answered Apr 01 '23 01:04

TypeIA