十六进制操作

时间:2015-10-31 18:22:12

标签: c++ mfc

BouncyCastle加密库(C#,Java)中有非常好的Hex.Decode(string hexString)Hex.ToHexString(byte[] hexArray)方法。

如何使用CString变量进行相同的转换,将{-1}}的十六进制字符串存储到"af010cdb",反之亦然?

2 个答案:

答案 0 :(得分:2)

这些很容易实现:

CString ToHexString(const CByteArray& Array)
{
    CString sHexString;
    for (int i=0; i<Array.GetSize(); i++)
        sHexString.AppendFormat(_T("%02X"), Array[i]);

    return sHexString;
}

void DecodeHexString(const CString& sHexString, CByteArray &Array)
{
    if (sHexString.IsEmpty())
        return;

    int nLen = sHexString.GetLength();

    if ((nLen % 2) != 0)
    {
        ASSERT(FALSE);
        return;
    }

    Array.SetSize(nLen/2);

    int nByte = 0;
    for(int i=0; i<nLen; i += 2)
    {
        CString sByte = sHexString.Mid(i, 2);
        BYTE byte = (BYTE)_tcstol(sByte, NULL, 16);
        Array[nByte] = byte;
        nByte++;
    }
}

答案 1 :(得分:0)

您还可以使用std::stringstd::vector<unsigned char>

修改:已移除sscanfsprintf

std::vector<unsigned char> str_to_byte(std::string str)
{
    std::vector<unsigned char> bytes;
    std::stringstream ss(str);
    std::string part;
    while (ss >> std::setw(2) >> part)
    {
        try {
            int i = std::stoi(part, 0, 16);
            bytes.push_back(static_cast<unsigned char>(i));
        }
        catch (...) {//error msg
        }
    }
    return bytes;
}

std::string byte_to_str(std::vector<unsigned char> bytes)
{
    std::stringstream ss;
    ss << std::hex << std::setfill('0') << std::uppercase;
    for (auto c:bytes) 
        ss << std::setw(2) << static_cast<unsigned int>(c);
    return ss.str(); 
}

int main()
{
    std::vector<unsigned char> bytes = str_to_byte("EF010203A0A1FFz");
    std::string str = byte_to_str(bytes);
    cout << str << endl; //should print "EF010203A0A1FF"
    return 0;
}