【问题标题】:boost::algorithm hex and unhex showing unexpected resultsboost::algorithm hex 和 unhex 显示出意外的结果
【发布时间】:2021-08-04 20:41:12
【问题描述】:

编辑:看起来我犯了一个愚蠢的错误:)

有人知道为什么下面的代码会产生 2 个不同的十六进制字符串吗?

开头似乎有一个额外的字节。 boost的十六进制和非十六进制不能很好地协同工作还是我错过了什么?欢迎使用 C++17 更好的替代品!

std::string hex(const std::vector<uint8_t>& v)
{
    std::string to;
    boost::algorithm::hex(v.begin(), v.end(), std::back_inserter(to));
    return to;
}

std::vector<uint8_t> unhex(const std::string& hex)
{
    std::vector<uint8_t> bytes = {0};
    boost::algorithm::unhex(hex, std::back_inserter(bytes));
    return bytes;
}

int main() 
{
    string payload = "01630B917123862732F0000002EF18";
    cout << payload << endl;
    cout << hex(unhex(payload)) << endl;
}

输出:

01630B917123862732F0000002EF18

0001630B917123862732F0000002EF18

【问题讨论】:

    标签: c++ boost hex


    【解决方案1】:

    额外的字节在这里:

        std::vector<uint8_t> bytes = {0};
    

    你应该像这样删除多余的字节:

        std::vector<uint8_t> bytes;
    

    【讨论】:

    • 啊。你知道我做了什么。它曾经是一个固定大小的数组,我使用 {0} 将它们全部初始化为 0。多么愚蠢的错误!谢谢!
    • 不要自责。像这样的初始化不一致是 C++ 遗留 C 兼容性的祸根。没有人认为他们是直觉的,你必须为此开发一个“危险雷达”。无论如何都不是一个愚蠢的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 2018-09-22
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多