This conversion in our daily coding still have a chance to meet, and here to share with you to discuss.
void Pu_hex_to_binary (std::string strhex, std::string &strbinaryresult) {for (int i = 0; i < strhex.size (); + + i) {char chtemp = strhex[i]; int chhexvalue; if (' F ' >= chtemp && chtemp >= ' a ') Chhexvalue = chtemp-' a ' + 10; else if (' F ' >= chtemp && chtemp >= ' a ') Chhexvalue = chtemp-' a ' + 10; else Chhexvalue = chtemp-' 0 '; Std::string strbinary; char ibit = 4; while (Ibit > 0) {if (chhexvalue% 2 = = 0) strbinary.push_back (' 0 '); else Strbinary.push_back (' 1 '); if (Chhexvalue > 0) chhexvalue >>= 1; --ibit; } std::reverse (Strbinary.begin (), Strbinary.end ()); Strbinaryresult.append (strbinary); }}void Pu_binary_to_hex (std::string strbinary, std::string &strhex) {int chhexvalue = 0; Strhex.clear (); for (int i= 0; I < strbinary.size (); ) {std::string strsubbinary; if (strbinary.size ()-I >= 4) {strsubbinary = Strbinary.substr (i, 4); i + = 4; } else {strsubbinary = Strbinary.substr (i); i = Strbinary.size (); } std::reverse (Strsubbinary.begin (), Strsubbinary.end ()); Chhexvalue = 0; for (int j = 0; J < strsubbinary.size (); ++j) {char chtemp = strsubbinary [j]; Char chbinaryvalue = chtemp-' 0 '; if (chbinaryvalue% 2 = = 1) chhexvalue + = 1 << j; } if (Chhexvalue <) strhex.push_back (Chhexvalue + ' 0 '); else Strhex.push_back (chHexValue-10 + ' A '); }}
Hex string Convert to binary string and Vise-versa (16 binary and 2 binary string conversions)