Thursday, May 22, 2008

Socket, byte order

사용하는 시스템의 architecture가 big-endian인지 little-endian인지를 알아야 보낼 데이터를 socket에서 사용하는 endian에 맞게 고쳐 보낼 수 있다. system의 endian을 알기 위한 테스트는 아래처럼 할 수 있다.

union btye_long {
long l;
unsigned char c[4];
}

int main()
{
union byte_long bl;
bl.l = 1200000L;
printf ("%02x-%02x-%02x-%02x\n", bl.c[0], bl.c[1], bl.c[2], bl.c[3]);
bl.l = htonl(bl.l);
printf ("%02x-%02x-%02x-%02x\n", bl.c[0], bl.c[1], bl.c[2], bl.c[3]);
return 0;
}
// from ALSP

근데, 이건 좀 복잡하고, 사실 if (120000L == htonl(120000L)) 만 해도 알 수 있다 ㅡ.ㅡ; 인텔 계열은 little endian 인데 반해 network packet에서는 bigendian을 사용한다. 그래서 항상 byte order를 변경해주어여 하는데 이때 사용하는 함수군이 아래와 같다.

  • htons host endian to network endian converting of 2bytes short

  • htonl host endian to network endian converting of 4bytes long

  • ntohs network endian to host endian converting of 2bytes short

  • ntohl network endian to host endian converting of 2bytes long


double, float 등의 변환은 ... 일단 생략 --;

No comments:

Post a Comment