【问题标题】:Convert hex string to character array in cpp [duplicate]在cpp中将十六进制字符串转换为字符数组[重复]
【发布时间】:2021-03-10 06:39:31
【问题描述】:

我在 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++ arrays string char hex


    【解决方案1】:

    我不是 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';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 2021-04-13
      • 2018-03-24
      • 2011-05-15
      • 2017-02-19
      • 2018-07-03
      • 2018-01-31
      相关资源
      最近更新 更多