___雖然簡單,但好記性不如爛筆頭___
//把字符串轉為數字 //支持16進制轉換,但是16進制字母必須是大寫的,且格式為以0X開頭的. //不支持負數 //*str:數字字符串指針 //*res:轉換完的結果存放地址. //返回值:0,成功轉換完成.其他,錯誤代碼. //1,數據格式錯誤.2,16進制位數為0.3,起始格式錯誤.4,十進制位數為0. unsigned char str2num(unsigned char *str,unsigned int *res) { unsigned int t; unsigned char bnum=0; //數字的位數 unsigned char *p; unsigned char hexdec=10;//默認為十進制數據 p=str; *res=0;//清零. while(1) { if((*p<='9'&&*p>='0')||(*p<='F'&&*p>='A')||(*p=='X'&&bnum==1))//參數合法 { if(*p>='A')hexdec=16; //字符串中存在字母,為16進制格式. bnum++; //位數增加. }else if(*p=='\0')break; //碰到結束符,退出. else return 1; //不全是十進制或者16進制數據. p++; } p=str; //重新定位到字符串開始的地址. if(hexdec==16) //16進制數據 { if(bnum<3)return 2; //位數小於3,直接退出.因為0X就占了2個,如果0X后面不跟數據,則該數據非法. if(*p=='0' && (*(p+1)=='X'))//必須以'0X'開頭. { p+=2; //偏移到數據起始地址. bnum-=2;//減去偏移量 }else return 3;//起始頭的格式不對 }else if(bnum==0)return 4;//位數為0,直接退出. while(1) { if(bnum)bnum--; if(*p<='9'&&*p>='0')t=*p-'0'; //得到數字的值 else t=*p-'A'+10; //得到A~F對應的值 *res+=t*usmart_pow(hexdec,bnum); p++; if(*p=='\0')break;//數據都查完了. } return 0;//成功轉換 }