簡體   English   中英

如何將一組十六進制字符串轉換為字節數組

[英]how to convert a set of hex strings to byte array

我輸入了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 );
}

這個答案假設輸入格式實際上是每個十六進制BYTE的3個字符。 我使用sscanf來簡化, streams顯然也是一種選擇。

    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM