最近做的东西涉及到从读取char数组中存放的十六进制数,每个char数据的码型(ASCII,BCD,FLOAT,HEX)不一样。需要进行对应数据类型的转换。实现如下:
string DataTrans::Char2BCD(unsigned char *c,int len)
{
char s[100];
char c1,c2;
string str="";
for(int i=0;i<len;i++)
{
c1= c[i]&0x0f;
c2= c[i]>>4;
int n=(int)(((c2&0x08+c2&0x04+c2&0x02+c2&0x01)<<4)+(c1&0x08+c1&0x04+c1&0x02+c1&0x01));
if(n<=9&&n>=0)
{
str+="0";
}
str+=itoa(n,s,10);
}
return str;
}
void DataTrans::Char2BYTE(unsigned char c, unsigned char *s)
{
for(int i=7;i>=0;i--)
{
s[i]=c&0x01;
c = c>>1;
}
}
float DataTrans::Char2Float(unsigned char *cp)
{
return *(float *)cp;
}
string DataTrans::Char2Hex(char a1)
{
string str = "";
//int n = (a1<<8)+a2;
int n=a1;
for (int i=2*sizeof(char) - 1; i>=0; i--)
{
str += "0123456789ABCDEF"[((n >> i*4) & 0xF)];
}
return str;
}
int DataTrans::Hex2Oct(unsigned char c1, unsigned char c2)
{
return (int)(c1<<8)+(int)c2;
}