#include "stdafx.h"
#include <afx.h> //Project->Settings->C/C++->CodeGeneration** :Debug mulitithreathed!
#include <math.h>
bool CheckMyString(CString str);
BYTE HexChar2Val(char ch);
BYTE HexStr2Byte(char *temp);
int CovertOurStr2Bytes(char * str, BYTE* buff);
bool CheckMyString(CString str)//¼ì²éºÏ·¨ÐÔ,ÒªÇóÊÇ16½øÖÆÊäÈ루ÓÐЧΪһ×Ö½ÚÐÍ,2¸ö×Ö·û£©
//²¢ÇÒÒÔ¿Õ¸ñ·Ö¿ª,Á¬ÐøÓÐЧ×Ö·ûΪ3¸ö¡¡Èç12 af 00 0 00 01
//Èç000 001 0af 0AF Ò²ÓÐЧ
//¶àÓÚÈýÔòΪ´íÎóµÄÈç00000001 000a 00ff af0 f00
{
//CString str=" 02 0 0 0FF 00f22 3 00 10 ff 21 56 75 a5 ";//valid !
//CStringstr=" 20 "; // valid !
//CStringstr=" F20 "; // invalid !
//CStringstr=" s2 0 0 0FF 0f 22 3 00 10 ff 21 56 75a5 "; // invalid !
int len=str.GetLength();
intcontns=0,constrain=3;
bool start=true;
for (inti=0;i<len;i++)
{
if(str.GetAt(i)==' '||str.GetAt(i)=='\0') //
{
contns=0;
start=true;
}
else if (isxdigit(str.GetAt(i))==0 )
return false;
else if(isxdigit(str.GetAt(i))!=0)// 16 TYPE
{
contns++; //continuous 16typechar number increases!
if(str.GetAt(i)=='0')
{
if(start) //if starts from 0, then contraint is 3
{
start=false;
constrain=3;
}
}
else if (start)//other '1'-...-'F'
{ //if starts from others,constrain is 2
start=false;
constrain=2;
}
if (contns>constrain)
returnfalse;
}
}
return true;
}
BYTE HexChar2Val(char ch) //turn 16 char into its value
{
BYTE ret;
if((ch>='0')&&(ch<='9')) //'0' ascii code is 48d (0x30)
ret= BYTE(ch-0x30);
else if((ch>='A')&&(ch<='F')) //'A' ascii code is65d
ret=BYTE(ch-'A'+10); //'F' 70d
elseif((ch>='a')&&(ch<='f')) //'a'ascii code is 97d
ret= BYTE(ch-'a'+10);
else
ret=BYTE(-1);
return ret;
}
BYTE HexStr2Byte(char *temp) //turn a 16 str to a byte typebyte
{
int len=strlen(temp);
BYTE ret=0;
for (inti=len-1;i>=0;i--)
ret=ret+HexChar2Val(temp[i])*BYTE(pow(16,len-1-i));
return ret;
}
int CovertOurStr2Bytes(char * str, BYTE* buff) //turn a 16 str(our specific) to byte type array
//return byte numbers
{
int len=strlen(str);
int i=0,buffindex=0;
char temp[]="";
//char*temp=""; //no!
for(i=0;i<len;i++)
{
if (str[i]!=' ')
{
sscanf(str+i,"%[^ ]%",temp);
i=i+strlen(temp);
buff[buffindex++]=HexStr2Byte(temp);
}
}
return buffindex;
}
int main(int argc, char* argv[])
{
CStringstr=" 02 FA 0 0FF 00f 22 3 00 10 ff 21 56 75a5 ";// valid !
//CString str=" 20 "; // valid!
//CString str=" F20 "; //invalid !
// CString str=" s2 0 0 0FF 000f 22 3 00 10 ff 2156 75 a5 "; // invalid !
bool chb=CheckMyString(str);
if(!chb)
{
printf("error input!\n");
return 0;
}
char *s=(char*)(LPCTSTR)(str);
BYTE buff[20]={0}; //16
printf("s is:%s,Length is %d\n",s,strlen(s));
int ret=CovertOurStr2Bytes(s,buff);
printf("buff is:");
for(int i=0;i<ret;i++)
{
printf("%d ",buff[i]);
}
printf("\nbufflength is %d\n",ret);
return 0;
}