如何将一组十六进制字符串转换为字节阵列

how to convert a set of hex strings to byte array

本文关键字:字符串 十六进制 转换 阵列 字节 一组      更新时间:2023-10-16

我有一个char *str = "13 00 0A 1B CA 00";

的输入

我需要输出为BYTE bytes[] = { 0x13, 0x00, 0x0A, 0x1B, 0xCA, 0x00 };

有人可以帮助解决方案吗?

您将需要解析两个字符中的每个字符,然后将它们转换为BYTE。这并不难。

std::stringstream converter;
std::istringstream ss( "13 00 0A 1B CA 00" );
std::vector<BYTE> bytes;
std::string word;
while( ss >> word )
{
    BYTE temp;
    converter << std::hex << word;
    converter >> temp;
    bytes.push_back( temp );
}

此答案假设输入格式实际上是每个十六进制字节的3个字符。我为简单起见使用sscanfstreams显然也是一个选择。

    std::vector<BYTE> bytes;
    char *str = "13 00 0A 1B CA 00";
    std::string input(str);
    size_t count = input.size()/3;
    for (size_t i=0; i < count; i++)
    {           
        std::string numStr = input.substr(i*3, input.find(" "));
        int num=0;
        sscanf(numStr.c_str(), "%x", &num);
        bytes.push_back((BYTE)num);
    }
    // You can access the output as a contiguous array at &bytes[0]
    // or just add the bytes into a pre-allocated buffer you don't want vector