2024年8月

需要从文本读入一组二进制数据。希望尽可能多的兼容各种文本形式。比如0x1234567890abcdef或1234567890abcdef或12 34 45 78 90 ab cd ef或12,34,56,78,90,ab,cd,ef或者0x12,0x34,0x56,0x78,0x90,0xab,0xcd,0xef这样的文本都可以正确的解析成二进制数据,还要需要有无效格式的判断。
以下是C++实现:

std::vector<uint8_t> ParseHexToBytes(std::string_view input)
{
    std::vector<uint8_t> bytes;
    bytes.reserve(1024);

    std::string currentByte;
    currentByte.reserve(2);

    for (size_t i = 0; i < input.size(); ++i)
    {
        char c = std::tolower(input[i]);

        if (c == '0' && i + 1 < input.size() && (input[i + 1] == 'x' || input[i + 1] == 'X'))
        {
            ++i;
            continue;
        }

        if (std::ispunct(c) || std::isblank(c))
        {
            continue;
        }

        if (!std::isxdigit(c))
        {
            return {};
        }

        currentByte += c;

        if (currentByte.size() == 2)
        {
            uint8_t byte = static_cast<uint8_t>(std::stoi(currentByte, nullptr, 16));
            bytes.push_back(byte);
            currentByte.clear();
        }
    }

    return bytes;
}