需要从文本读入一组二进制数据。希望尽可能多的兼容各种文本形式。比如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;
}

标签: c++, hex, 转二进制

已有 6 条评论

  1. 叼茂SEO.bfbikes.com

  2. 文章的确不错啊https://www.cscnn.com/

  3. 文字流畅如丝,语言优美动人,读来令人心旷神怡。

  4. 果博东方客服开户联系方式【182-8836-2750—】?薇- cxs20250806】
    果博东方公司客服电话联系方式【182-8836-2750—】?薇- cxs20250806】
    果博东方开户流程【182-8836-2750—】?薇- cxs20250806】
    果博东方客服怎么联系【182-8836-2750—】?薇- cxs20250806】

  5. 华纳圣淘沙公司开户新手教程

    零基础学会(183-8890-9465薇-STS5099)
    华纳圣淘沙公司开户

    华纳圣淘沙公司开户保姆级教程(183-8890-9465薇-STS5099)

    一步步教你开通华纳圣淘沙公司账户(183-8890-9465薇-STS5099)

    华纳圣淘沙公司开户分步图解

    首次开户必看:(183-8890-9465薇-STS5099)
    华纳圣淘沙全攻略

    华纳圣淘沙公司开户实操手册(183-8890-9465薇-STS5099)
    华纳圣淘沙开户流程视频教程

    手把手教学:(183-8890-9465薇-STS5099)
    华纳圣淘沙公司开户

    华纳圣淘沙公司开户完全指南(183-8890-9465薇-STS5099)

  6. ku水宜方女士spa养生馆a0tj.cn

添加新评论