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;
c/c++ bytes与int,short,long,float,double相互转换
猜你喜欢
转载自blog.csdn.net/lzp_k2/article/details/83659159
今日推荐
周排行