这个转换在我们日常的编码中还是很有机会遇到的,这里贴出来和大家分享探讨。

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 < 10)
            strHex.push_back(chHexValue + '0');
        else
            strHex.push_back(chHexValue - 10 + 'A');
    }
}

  

posted on 2016-05-09 17:38  xsgluozi  阅读(377)  评论(0编辑  收藏  举报