Hex string Convert to binary string and Vise-versa (16 binary and 2 binary string conversions)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.