二进制值和十六进制字符串相互转换的C++代码

#include <iostream>
#include <string>
#include <stdint.h>

using namespace std;

string BinToHex(const string &strBin, bool bIsUpper = false)
{
    string strHex;
    strHex.resize(strBin.size() * 2);
    for (size_t i = 0; i < strBin.size(); i++)
    {
        uint8_t cTemp = strBin[i];
        for (size_t j = 0; j < 2; j++)
        {
            uint8_t cCur = (cTemp & 0x0f);
            if (cCur < 10)
            {
                cCur += '0';
            }
            else
            {
                cCur += ((bIsUpper ? 'A' : 'a') - 10);
            }
            strHex[2 * i + 1 - j] = cCur;
            cTemp >>= 4;
        }
    }

    return strHex;
}

string HexToBin(const string &strHex)
{
    if (strHex.size() % 2 != 0)
    {
        return "";
    }

    string strBin;
    strBin.resize(strHex.size() / 2);
    for (size_t i = 0; i < strBin.size(); i++)
    {
        uint8_t cTemp = 0;
        for (size_t j = 0; j < 2; j++)
        {
            char cCur = strHex[2 * i + j];
            if (cCur >= '0' && cCur <= '9')
            {
                cTemp = (cTemp << 4) + (cCur - '0');
            }
            else if (cCur >= 'a' && cCur <= 'f')
            {
                cTemp = (cTemp << 4) + (cCur - 'a' + 10);
            }
            else if (cCur >= 'A' && cCur <= 'F')
            {
                cTemp = (cTemp << 4) + (cCur - 'A' + 10);
            }
            else
            {
                return "";
            }
        }
        strBin[i] = cTemp;
    }

    return strBin;
}

int main()
{
    string strBin = "!@#$%^&*()_+~`1234567890-=";
    string strHex = "21402324255E262A28295F2B7E60313233343536373839302D3D";

    string strBinToHex = BinToHex(strBin);
    cout << strBinToHex << endl;
    strBinToHex = BinToHex(strBin, true);
    cout << strBinToHex << endl;

    string strHexToBin = HexToBin(strHex);
    cout << strHexToBin << endl;

    return 0;
}

展开阅读全文

没有更多推荐了,返回首页