Do MFC serial port when sending, generally use CEdit control as Send input box, usually send input box associated with a CString variable, through UpdateData update, most cases we need to use hexadecimal send, but CString default is the string format, For example, input box input 11 22 33 44 55, in fact, the content "one to a page of a", we want to convert it to 0X11,0X22,0X33,0X44,0XAA.
So how to implement, by the following 2 functions implemented
1 //Converts a string into a byte array as a hexadecimal string, separated by spaces between bytes,2 //returns the length of the converted byte array, with the length of the byte array set automatically. 3 //Description: Convert string str[]= "one to one" to 0x11,0x22,0x33,0x44,0xaa4 intCmfc_uart20160921dlg::str2hex (CString str,Char*data)5 {6 intT, T1;7 intRlen =0, Len =Str. GetLength ();8 //data. SetSize (LEN/2);9 for(inti =0; i<Len;)Ten { One CharL, H =Str[i]; A if(H = =' ') - { -i++; the Continue; - } -i++; - if(I >=len) + Break; -L =Str[i]; +t =Hexchar (h); AT1 =Hexchar (l); at if(T = = -) || (T1 = = -)) - Break; - Else -t = T * -+T1; -i++; -Data[rlen] = (Char) T; inrlen++; - } to returnRlen; + } - the CharCmfc_uart20160921dlg::hexchar (Charc) * { $ if(c >='0') && (c <='9'))Panax Notoginseng returnA O0x30; - Else if(c >='A') && (c <='F')) the returnA O'A'+Ten; + Else if(c >='a') && (c <='F')) A returnC'a'+Ten; the Else + return 0x10; -}
The test code is as follows
Char data[]; // Hex Send int Ilen = Str2hex (m_editsend,data),//m_editsend is the Ceit variable associated with CString controlpthreadcom->senddata ( BYTE *) data, Ilen); // send data via serial port
MFC input Box CEdit control hexadecimal conversion