【原】高地位转换 统一一个函数完成

这是使用C++的模版特化实现多个类型同一个函数完成高地位转换。

#include <iostream>

template <class T> T transform(T& b)
{
return b;
}
template <> int transform<int>(int& b)//4字节
{
return (((b & 0xff000000) >> 24)|((b & 0x00ff0000) >> 8)|\
((b & 0x0000ff00) << 8)|((b & 0x000000ff) << 24));
}

template <> unsigned int transform<unsigned int>(unsigned int& b)//4字节
{
return (((b & 0xff000000) >> 24)|((b & 0x00ff0000) >> 8)|\
((b & 0x0000ff00) << 8)|((b & 0x000000ff) << 24));
}

template <> short int transform<short int>(short int& b)//2字节
{
return (((b&0xff00)>>8)|((b&0x00ff)<<8));
}

template <> unsigned short int transform<unsigned short int>(unsigned short int& b)//2字节
{
return (((b&0xff00)>>8)|((b&0x00ff)<<8));
}

template <> long int transform<long int>(long int& b)//4字节
{
return (((b & 0xff000000) >> 24)|((b & 0x00ff0000) >> 8)|\
((b & 0x0000ff00) << 8)|((b & 0x000000ff) << 24));
}

template <> unsigned long int transform<unsigned long int>(unsigned long int& b)//4字节
{
return (((b & 0xff000000) >> 24)|((b & 0x00ff0000) >> 8)|\
((b & 0x0000ff00) << 8)|((b & 0x000000ff) << 24));
}

template <> float transform<float>(float& b)//4字节
{
float tmp;
char* tmp1=(char*)&tmp;
char* tmp2=(char*)&b;
memcpy(tmp1,tmp2+3,1);
memcpy(tmp1+1,tmp2+2,1);
memcpy(tmp1+2,tmp2+1,1);
memcpy(tmp1+3,tmp2,1);
return tmp;
}

template <> double transform<double>(double& b)//8字节
{
double tmp;
char* tmp1=(char*)&tmp;
char* tmp2=(char*)&b;
memcpy(tmp1,tmp2+7,1);
memcpy(tmp1+1,tmp2+6,1);
memcpy(tmp1+2,tmp2+5,1);
memcpy(tmp1+3,tmp2+4,1);
memcpy(tmp1+4,tmp2+3,1);
memcpy(tmp1+5,tmp2+2,1);
memcpy(tmp1+6,tmp2+1,1);
memcpy(tmp1+7,tmp2,1);
return tmp;
}

template <> long double transform<long double>(long double& b)//8字节
{
long double tmp;
char* tmp1=(char*)&tmp;
char* tmp2=(char*)&b;
memcpy(tmp1,tmp2+7,1);
memcpy(tmp1+1,tmp2+6,1);
memcpy(tmp1+2,tmp2+5,1);
memcpy(tmp1+3,tmp2+4,1);
memcpy(tmp1+4,tmp2+3,1);
memcpy(tmp1+5,tmp2+2,1);
memcpy(tmp1+6,tmp2+1,1);
memcpy(tmp1+7,tmp2,1);
return tmp;
}

int main()
{
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值