首页 > 解决方案 > 在cpp中将十六进制字符串转换为字符数组

问题描述

我在 cpp 中有一个十六进制字符串

std::string str = "fe800000000000000cd86d653903694b";

我想将它转换为一个 char 数组,它像这样存储它

unsigned char ch[16] =     { 0xfe, 0x80, 0x00, 0x00,
                             0x00, 0x00, 0x00, 0x00,
                             0x0c, 0xd8, 0x6d, 0x65,
                             0x39, 0x03, 0x69, 0x4b };

我正在考虑一次遍历字符串 2 个字符并将其存储在字符数组中。但是我在这里找不到任何有帮助的库函数。

for (size_t i = 0; i < str.length(); i += 2) 
{ 
      string part = hex.substr(i, 2); 
      //convert part to hex format and store it in ch
}

任何帮助表示赞赏

标签: c++arraysstringcharhex

解决方案


我不是 C++ 专家,肯定有更好的东西,但因为没有人回答......

#include <iostream>

int main()
{
    std::string str = "fe800000000000000cd86d653903694b";
    unsigned char ch[16];

    for (size_t i = 0; i < str.length(); i += 2) 
    { 
        // Assign each pair converted to an integer
        ch[i / 2] = std::stoi(str.substr(i, 2), nullptr, 16);
    }
    for (size_t i = 0; i < sizeof ch; i++) 
    { 
        // Print each character as hex
        std::cout << std::hex << +ch[i];
    }
    std::cout << '\n';
}

str如果你事先不知道长度:

#include <iostream>
#include <vector>

int main()
{
    std::string str = "fe800000000000000cd86d653903694b";
    std::vector<unsigned char> ch;

    for (size_t i = 0; i < str.length(); i += 2) 
    { 
        ch.push_back(std::stoi(str.substr(i, 2), nullptr, 16));
    }
    for (size_t i = 0; i < ch.size(); i++) 
    { 
        std::cout << std::hex << +ch[i];
    }
    std::cout << '\n';
}

推荐阅读