이번 글에서는 엔디안에 대해 간단히 알아보고 Visual C++에서 어떻게 변환해야하는지 알아보겠습니다.
엔디안은 컴퓨터 메모리에 연속된 대상을 배열하는 방법을 말하며 바이트를 배열하는 방법을 말합니다.
엔디안은 리틀엔디안, 빅엔디안, 미들엔디안이 있으며, 리틀엔디안 빅엔디안의 차이는 아래와 같습니다.

프로세서는 CPU아키텍쳐에 따라 다를수 있습니다만 네트워크상에서는 빅엔디안을 사용합니다.
빅엔디안과 리틀엔디안의 저장 방식을 가시적으로 보면 아래와 같습니다.


해당 저장 방식을 고려해야하는 때는 보통 서로 다른 프로세서끼리 통신을 해야할 때 엔디안이 다를 경우입니다.
그럴 경우 htons, ntohs, htonl, ntohl 함수를 사용하여 조정을 해줘야합니다.
해당 코드를 사용하기 위한 헤더파일과 라이브러리는 아래와 같습니다.

함수에 대한 설명은 아래와 같습니다.

htons와 ntohs, htonl과 ntohl의 차이는 form to의 차이이고 입력과 출력에 대한 값은 같습니다.
예제 소스는 아래와 같습니다.
#include "WinSock2.h"
#pragma comment( lib, "Ws2_32.lib" )
void main ()
{
unsigned short usBig = 0x1234;
unsigned short usLittle = htons( usBig ); // host to network
// unsigned short usLittle = ntohs( usBig ); // network to host
cout << "0x" << hex << usBig << endl;
cout << "0x" << hex << usLittle << endl;
unsigned int uiBig = 0x12345678;
unsigned int uiLittle = htonl( uiBig ); // host to network
//unsigned int uiLittle = ntohl( uiBig ); // network to host
cout << "0x" << hex << uiBig << endl;
cout << "0x" << hex << uiLittle << endl;
system( "pause" );
}