最近遇到在文件存储时要对及诶按数据进行数据类型的转换后才可以进行保存,学习到了这两种方法:
1、可以用以下方
#include "string.h"
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 ts = 400;
unsigned char *p = T2bytes<int>(ts);
ts= bytes2T<int>(p);
2、也可以用union
typedef union {
/*unsigned*/ int integer = 0;
/*unsigned*/ char byte[4];
} INTUCHAR;
INTUCHAR ts;
ts.integer = 400;
//ts.byte[0],ts.byte[1],ts.byte[2],ts.byte[3];
3、
temp.textInfo.nTextNum[0] = (char)(nTextNum & 0xff);
temp.textInfo.nTextNum[1] = (char)((nTextNum >> 8) & 0xff);
temp.textInfo.nTextNum[2] = (char)((nTextNum >> 16) & 0xff);
temp.textInfo.nTextNum[3] = (char)((nTextNum >> 24) & 0xff);
4、
itoa(nTextNum,temp.textInfo.nTextNum,10);///itoa函数接受三个参数,第一个参数是要转化的数字,第二个是转化为字符串后存放的位置,最后一个可以指定进制,如这里使用的是十进制。