链接
参考链接: link.
代码
// An highlighted block
template<class T>
void ConvertT2Byte(T dou, unsigned char* temp)
{
unsigned char* pdata = (unsigned char *)&dou;
int sizeofT = sizeof(dou);
switch (sizeofT)
{
case 4:
for (int i = 0; i < 4; i++)
{
temp[i] = *pdata++;
}
break;
case 8:
for (int i = 0; i < 8; i++)
{
temp[i] = *pdata++;
}
break;
default:
break;
}
}
template<class T>
T ConvertByte2T(unsigned char *temp)
{
T CurrentReceiveData = 0;
void *pf;
pf = &CurrentReceiveData;
unsigned char * px;
px = (unsigned char *)temp;
int sizeofT = sizeof(CurrentReceiveData);
switch (sizeofT)
{
case 4:
for (int j = 0; j < 4; j++)
{
*((unsigned char *)pf + j) = *(px + j);
}
break;
case 8:
for (int j = 0; j < 8; j++)
{
*((unsigned char *)pf + j) = *(px + j);
}
break;
default:
break;
}
return CurrentReceiveData;
}
int main()
{
double dou = 101123.456894;
unsigned char temp1[8];
ConvertT2Byte<double>(dou,temp1);
double re = ConvertByte2T<double>(temp1);
cout << std::fixed;
cout << re << endl;
float flo = 101123.456894;
unsigned char flotemp[8];
ConvertT2Byte(flo, flotemp);
float fl = ConvertByte2T<float>(flotemp);
cout << fl << endl;
int in = 1243;
unsigned char inttemp[4];
ConvertT2Byte(in,inttemp);
int inre = ConvertByte2T<int>(inttemp);
cout << inre << endl;
cout << endl;
cout << endl;
}