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

/ C++ / 没有评论 / 1788浏览
#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;
}
// 高阶写法,std::endian需要支持C++20支持,byteswap需要C++23支持


/*
    只在小端机器上转换成网络字节序,在大端机器上什么都不做
*/
template<class T>
T HostToNetWork(T t)
{
    if constexpr(std::endian::native == std::endian::big)
    {
        return t;
    }
    else if constexpr(std::endian::native == std::endian::little)
    {
        return byteswap(t);
    }
}

/*
    只在小端机器上转换成主机序,在大端机器上什么都不做
*/
template<class T>
T NetWorkToHost(T t)
{
    if constexpr(std::endian::native == std::endian::big)
    {
        return t;
    }
    else if constexpr(std::endian::native == std::endian::little)
    {
        return byteswap(t);
    }
}
#include <stdint.h>
#include <byteswap.h>
#include <bit>

namespace asid
{
    template<class T>
    T byteswap(T value)
    {
        if constexpr(sizeof(T) == sizeof(uint16_t))
        {
            return (T)bswap_16((uint16_t)value);
        }
        else if constexpr(sizeof(T) == sizeof(uint32_t))
        {
            return (T)bswap_32((uint32_t)value);
        }
        else if constexpr(sizeof(T) == sizeof(uint64_t))
        {
            return (T)bswap_32((uint64_t)value);
        }
    }
}