这是使用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;
}