eATM

c++,字节数组与十六进制字符串互转.

std::string util::hex_to_binary(std::string_view&& src_hex)
{
    ASSERT(src_hex.size() % 2 == 0);
    if (src_hex.size() % 2 != 0 || src_hex.empty()) return "";

    std::string outputString;
    outputString.resize(src_hex.size() / 2);
    char* lpOutBuffer = outputString.data();

    auto src_length = src_hex.size();

    for (size_t i = 0; i < src_length; i++)
    {
        int	    tmpD = 0;
        auto tmpBit = src_hex[i];
        if (tmpBit == 'A' || tmpBit == 'a') tmpD = 10;
        else if (tmpBit == 'B' || tmpBit == 'b') tmpD = 11;
        else if (tmpBit == 'C' || tmpBit == 'c') tmpD = 12;
        else if (tmpBit == 'D' || tmpBit == 'd') tmpD = 13;
        else if (tmpBit == 'E' || tmpBit == 'e') tmpD = 14;
        else if (tmpBit == 'F' || tmpBit == 'f') tmpD = 15;
        else if (tmpBit >= '0' && tmpBit <= '9')
        {
            tmpD = tmpBit - '0';
        }
        else {
            return "";
        }

        if (i % 2 == 0)	
        {
            tmpD *= 0x10;	
            *lpOutBuffer = tmpD;
        }
        else {
            *lpOutBuffer += tmpD;
            lpOutBuffer++;
        }
    }
    return outputString;
}

std::string util::binary_to_hex(std::string_view&& src_bytes)
{
    auto src_length = src_byte.size();
    std::string ouputString;
    ouputString.resize(src_byte.size() * 2);
    unsigned char const Hex[] = "0123456789ABCDEF";
    for (size_t i = 0; i < src_length; i++)
    {
        unsigned char binByte = src_byte[i];
        ouputString[2 * i] = (Hex[(binByte & 0xf0) >> 4]);
        ouputString[2 * i + 1] = (Hex[binByte & 0x0f]);
    }
    return ouputString;
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注