int64、double字节序转换(大小端)

#include 
#include  // 包含windows.h就不要包含这个头文件了
#pragma comment(lib, "Ws2_32.lib")

struct int64tonet
{
	union
	{
		__int64 w_;
		int r_[2];
	}w, r;

	int64tonet(__int64 i)
	{
		w.w_ = i;
		r.r_[0] = htonl(w.r_[1]);
		r.r_[1] = htonl(w.r_[0]);
	}

	__int64 operator()()
	{
		return r.w_;
	}
};

#define INT64_TO_NET(val)	((__int64) ( \
      (((__int64) (val) &						\
	(__int64) (0x00000000000000ffU)) << 56) |	\
      (((__int64) (val) &						\
	(__int64) (0x000000000000ff00U)) << 40) |	\
      (((__int64) (val) &						\
	(__int64) (0x0000000000ff0000U)) << 24) |	\
      (((__int64) (val) &						\
	(__int64) (0x00000000ff000000U)) <<  8) |	\
      (((__int64) (val) &						\
	(__int64) (0x000000ff00000000U)) >>  8) |	\
      (((__int64) (val) &						\
	(__int64) (0x0000ff0000000000U)) >> 24) |	\
      (((__int64) (val) &						\
	(__int64) (0x00ff000000000000U)) >> 40) |	\
      (((__int64) (val) &						\
	(__int64) (0xff00000000000000U)) >> 56)))

int main(int, char **)
{
	__int64 i = 0x1122334455667788;
	int64tonet j(i);
	__int64 m = j();
	__int64 n = INT64_TO_NET(i);
	std::cout << std::hex << m << std::endl;
	std::cout << std::hex << n << std::endl;

	system("pause");
}
// int64网络字节序转换为主机字节序
inline __int64 ntoh_int64(__int64 val)
{
    __int64 ret = val;
#if __BYTE_ORDER == __LITTLE_ENDIAN
    ret = (((__int64)ntohl((unsigned long)val)) << 32) | ntohl((unsigned long)(val>>32));
#endif
    return ret;
}

// double网络字节序转换为主机字节序
inline double ntoh_double(double val)
{
    double ret = val;
#if __BYTE_ORDER == __LITTLE_ENDIAN
    __int64 tmp = ntoh_int64(*((__int64*)&val));
    ret = *((double*)&tmp);
#endif
    return ret;
}


你可能感兴趣的:(c/c++,network)