template<typename T>
static T bytes2T(unsigned char *bytes)
{
T res = 0;
int n = sizeof(T);
memcpy(&res, bytes, n);
return res;
}
template<typename T>
static unsigned char * T2bytes(T u)
{
int n = sizeof(T);
unsigned char* b = new unsigned char[n];
memcpy(b, &u, n);
return b;
}
// 相关测试代码
// int d = 267;
// unsigned char *p = T2bytes<int>(d);
// for(int i = 0; i<sizeof(d); i++)
// {
// printf("p[%d]=0xX\n", i, p[i]);
// }
// d = bytes2T<int>(p);
// printf("d=%d\n", d);
// delete []p;
//
// float f = 257.1;
// p = T2bytes<float>(f);
// for(int i = 0; i<sizeof(f); i++)
// {
// printf("p[%d]=X\n", i, p[i]);
// }
// f = bytes2T<float>(p);
// printf("f=%.1f\n", f);
// delete []p;
static T bytes2T(unsigned char *bytes)
{
}
template<typename T>
static unsigned char * T2bytes(T u)
{
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

本文介绍了一种通用模板方法,用于实现不同数据类型与字节串之间的相互转换。其中包括将字节串转换为特定数据类型(如整数或浮点数),以及将数据类型转换为字节串的方法。通过示例展示了整数和浮点数的转换过程。

2298

被折叠的 条评论
为什么被折叠?



