32位数从主机字节顺序转换成网络字节顺序

/ C++ / 没有评论 / 120浏览
#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")

using namespace std;

//unsigned long long htonll(unsigned long long val)
//{
//	return (((unsigned long long)htonl((int)((val<<32)>>32)))<<32) | (unsigned int)htonl((int)(val>>32));
//}

template<typename T>
auto Swap(T val) -> decltype(val)
{
	if (std::is_same<T, unsigned short>::value)
	{
		return htons(val);
	}
	else if (std::is_same<T, int32_t>::value)
	{
		return htonl(val);
	}
	return val;
}

int main()
{
	int32_t aa = 27;
	aa = Swap(aa);


	std::cout << aa << std::endl;

	system("PAUSE");
	return 0;
}