在c ++中将字符串数组转换为字节数组

时间:2013-10-15 08:43:10

标签: c++

我有一个字符串说:

string abc = "1023456789ABCD"

我想将其转换为字节数组,如:

byte[0] = 0x10;
byte[1] = 0x23;
byte[2] = 0x45; 
----

等等

我在这里检查了一些帖子但找不到合适的解决方案。 任何帮助将不胜感激。 在此先感谢。

2 个答案:

答案 0 :(得分:3)

查看 Live on Coliru

#include <string>
#include <cassert>

template <typename Out>
void hex2bin(std::string const& s, Out out) {
    assert(s.length() % 2 == 0);

    std::string extract;
    for (std::string::const_iterator pos = s.begin(); pos<s.end(); pos += 2)
    {
        extract.assign(pos, pos+2);
        *out++ = std::stoi(extract, nullptr, 16);
    }
}

#include <iostream>
#include <vector>

int main()
{
    std::vector<unsigned char> v;

    hex2bin("1023456789ABCD", back_inserter(v));

    for (auto byte : v)
        std::cout << std::hex << (int) byte << "\n";
}

输出

10
23
45
67
89
ab
cd

答案 1 :(得分:-1)

当你说'byte'时,你看起来就像是以十六进制表示的每个字符。

在这种情况下,你可以简单地使用string.c_str(),因为这只是一个c风格的字符串(char*)。

byte[2] = 0x45

相同
byte[2] = 69; //this is 0x45 in decimal

如果您想单独存储数组,可以将string.c_str()的输出分配给另一个char*