htons()

왜 필요한가?

https://m.blog.naver.com/wndrlf2003/70190031633

http://forum.falinux.com/zbxe/index.php?document_srl=431494&mid=C_LIB

호스트의 바이트 순서를 Big Endian 방식인 Network 바이트 방식으로 바꾸어 준다.

host to network short 의 약자이다.

short이므로 2바이트이다

내 구현

unsigned short my_htons(int tmp)
{
	unsigned short inp = (unsigned short)tmp;
	unsigned short a = 0;
	if (BYTE_ORDER == BIG_ENDIAN)
		return (inp);
	for (int i = 0; i < 2; i++)
	{
		a += (inp % 16) << ((i + 2) * 4);
		inp /= 16;
	}
	for (int i = 0; i < 2; i++)
	{
		a += (inp % 16) << (i * 4);
		inp /= 16;
	}
	return (a);
}

테케

void htons_test()
{
	//unsigned short port = 0x1234;// 0x04d2; htons expected result : 0xd204

	unsigned short port = 9999; 
	//test();
	printf("%x\\n", port);
	printf("%x\\n", htons(port));
	printf("%x\\n", port);
	printf("%x\\n", my_htons(port));
	//std::cout << htons(port) << std::endl
}

메인문

int main(void)
{
	htons_test();
	return (0);
}

개쉽게 구현하는법

#define HTONS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))