项目中遇到了串口通讯的问题。想看一下从串口中读出的数据,读出的数据我放在了一个TCHAR指针变量里,发现在变成十六进制字符串输出时,本来的0xf2,变完之后会成为ffffff2(几个f忘了),换了几个变换方式,都是这样的问题。后来才想到,是符号的问题。需要先把变量转换成无符号的整数,再转换为十六进制。我想到的是将TCHAR强制转换为BYTE,试了下可行。

 
  
  1. void CMagneticEq::Output(const BYTE *data, int len)  
  2. {  
  3.     static int num=0;  
  4.     CString temp;  
  5.     temp.Format(_T("begin%d:"),num++);  
  6.     CString ttttt;  
  7.     for (int i=0;i<len;i++)  
  8.     {  
  9.         //itoa(data[i],test,16);  
  10.         ttttt.Format("%x",data[i]);  
  11.         temp+=ttttt;  
  12.         temp+=" ";  
  13.     }  
  14.     temp+="\r\n";  
  15.     CString ScriptError=_T("D:\\Output.txt");  
  16.     CFile m_ScriptError;  
  17.     BOOL st = m_ScriptError.Open(ScriptError,CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite);  
  18.     if (st == FALSE)  
  19.     {  
  20.         AfxMessageBox("打开文件D:\\Output.txt失败!");  
  21.         //return FALSE;  
  22.     }  
  23.     else  
  24.     {  
  25.         m_ScriptError.SeekToEnd();  
  26.         m_ScriptError.Write(temp,temp.GetLength());  
  27.         m_ScriptError.Flush();  
  28.         m_ScriptError.Close();  
  29.     }