C++ boost::算法hex和unhex显示意外结果

C++ boost::算法hex和unhex显示意外结果,c++,boost,hex,C++,Boost,Hex,编辑:看来我犯了个愚蠢的错误:) 有人知道为什么下面的代码会产生两个不同的十六进制字符串吗 开头似乎有一个额外的字节。boost的hex和unhex是否不能很好地协同工作,或者我遗漏了什么?更好的选择欢迎使用C++17 std::string hex(const std::vector<uint8_t>& v) { std::string to; boost::algorithm::hex(v.begin(), v.end(), std::back_inser

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

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

开头似乎有一个额外的字节。boost的hex和unhex是否不能很好地协同工作,或者我遗漏了什么?更好的选择欢迎使用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;
}
std::string十六进制(const std::vector&v)
{
std::字符串到;
boost::algorithm::hex(v.begin(),v.end(),std::back_inserter(to));
返回;
}
标准::向量unhex(常量标准::字符串和十六进制)
{
std::vector bytes={0};
boost::algorithm::unhex(十六进制,std::back_插入器(字节));
返回字节;
}
int main()
{
字符串有效载荷=“01630B917123862732F0000002EF18”;

cout额外的字节在这里:

    std::vector<uint8_t> bytes = {0};
std::vector bytes={0};
您应该删除额外的字节,如下所示:

    std::vector<uint8_t> bytes;
std::向量字节;

Ahh。你知道我做了什么。它过去是一个固定大小的数组,我用{0}将它们全部初始化为0。这是一个愚蠢的错误!谢谢!不要自责。像这样的初始化不一致是C++遗留C兼容性的祸根。没有人认为它们是直观的,你必须开发一个“危险雷达”对它来说,绝对不是一个愚蠢的错误。