C++ 實現string轉BYTE


用於將形如"0x1A"的string轉成BYTE類型

代碼如下, 有問題歡迎指出

 

 1 bool str2byte(const std::string &str, BYTE &bRet)
 2 {
 3   bRet = 0x00;       //結果
 4   size_t iPos = 1;   //
 5   size_t power = 1;  //冪次
 6 
 7   //沒找的'x'返回
 8   if(std::string::npos == str.find("x"))
 9   {
10     return false;
11   }
12 
13   //從右往左依次取每個字符
14   while (str.find("x") != (str.length()-iPos))
15   {
16     char cVal = str[str.length()-iPos];
17     int iVal = int(cVal);
18 
19     //0~9
20     if ((iVal >= 48) && (iVal <= 57))
21     {
22       bRet += ((iVal-48) * power);
23     }
24     //A~F
25     else if ((iVal >= 65) && (iVal <= 70))
26     {
27       bRet += ((iVal-55) * power);
28     }
29     //a~f
30     else if ((iVal >= 97) && (iVal <= 102))
31     {
32       bRet += ((iVal-87) * power);
33     }
34 
35     ++iPos;
36     power *= 16;
37   }
38 
39   return true;
40 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM