int CSerialPort::str2Hex(CString str, CString &data)
{
int t,t1;
int rlen=0,len=str.GetLength();
if(!((len-1)%2))
{
rlen=0;
return rlen;
}
LPTSTR pBuffer = data.GetBuffer((len+1)/2);
for (int i=0;i
{
char l,h=str[i];
if (h==' ')
{
i++;
continue;
}
i++;
if (i>=len)
break;
l=str[i];
t=HexChar(h);
t1=HexChar(l);
if (t==-1||t1==-1)
{
rlen = -1;
break;
}
if ((t==16)||(t1==16))
break;
else
t=t*16+t1;
i++;
pBuffer[rlen]=(char)t;
rlen++;
}
data.ReleaseBuffer();
return rlen;
}
char CSerialPort::HexChar(char c)
{
if ((c>='0')&&(c<='9'))
return c-0x30;
else if ((c>='A')&&(c<='F'))
return c-'A'+10;
else if((c>='a')&&(c<='f'))
return c-'a'+10;
else
return -1;
}
void CSerialPort::HexToAscii(BYTE *Temp,CString &data,int Len)
{
LPTSTR pBuff=data.GetBuffer(Len*2);
char sztemp[2];
for (int i=0;i
{
sztemp[0]=Temp[i]/16;
if (sztemp[0]>0x09)
sztemp[0]=sztemp[0]-0x0a+'A';
else
sztemp[0]+=0x30;
sztemp[1]=Temp[i]%16;
if (sztemp[1]>0x09)
sztemp[1]=sztemp[1]-0x0a+'A';
else
sztemp[1]+=0x30;
pBuff[i*2]=sztemp[0];
pBuff[i*2+1]=sztemp[1];
}
data.ReleaseBuffer();
}
int ascii_to_hex(char* str, unsigned char* buf, int* size)
{
int i;
int len=strlen(str);
if(len%2){
fprintf(stderr, "ascii can't conver to hex,no't even number\n");
return -1;
}
for(i = 0; i < len;i += 2)
{
int val = 0;
char tmp_buf[3];
memset(tmp_buf, 0, sizeof(tmp_buf));
memcpy(tmp_buf, &str[i], 2);
sscanf(tmp_buf, "%x", &val);
buf[i / 2] = (unsigned char)val;
}
*size=i/2;
return 0;
}
阅读(1177) | 评论(0) | 转发(0) |