将std :: string转换为字节数组

时间:2016-10-30 22:58:46

标签: c++

所以我有一串字节,例如

std::string bytes = "55DEBEFF4A";

我想把它们读成一个unsigned char数组。

unsigned char* myArray = new unsigned char[len];

最好的办法是什么?我想以myArray [0]为0x55来访问它 myArray [1]为0xDE

谢谢!

4 个答案:

答案 0 :(得分:1)

看一下以下问题的答案,我认为它们会帮助您找到解决问题答案的方法:

答案 1 :(得分:1)

这不是字节。他们是人物。要将前两个字符转换为值,您需要这样的内容:

int value = ((bytes[0] - '0') << 8) + bytes[1] - '0';

答案 2 :(得分:0)

首先,如果要使用十六进制,则需要编写数字0x55DEBEFF4A。 您不能将整数分配给字符串。我认为你最好的解决方案是直接创建你的数组:

unsigned char myArray[] = { 0x55, 0xDE, 0xBE, 0xFF, 0x4A };

编辑:正如Galik所说,你也可以这样做:

std::string bytes = "\x55\xDE\xBE\xFF\x4A";
unsigned char myArray[] = bytes.c_str();

答案 3 :(得分:0)

所以你有文字阅读“55DEBEFF4A”。让我们假设这是ASCII,因为它比替代品更难和更少见。要将其转换为字节,您将需要处理字符并逐个字符地转换吸盘。

以下是一些可疑的方法来进行翻译,希望能提出更好的方法。

一种丑陋的基于地图的方法:

std::map<char, int> cnv
{
    {'0',  0},
    {'1',  1},
    {'2',  2},
    {'3',  3},
    {'4',  4},
    {'5',  5},
    {'6',  6},
    {'7',  7},
    {'8',  8},
    {'9',  9},
    {'a', 10},
    {'b', 11},
    {'c', 12},
    {'d', 13},
    {'e', 14},
    {'f', 15},
    {'A', 10},
    {'B', 11},
    {'C', 12},
    {'D', 13},
    {'E', 14},
    {'F', 15}
};
std::vector<uint8_t> binarray(const std::string & in)
{
    std::vector<uint8_t> out;
    bool newnum = true;
    size_t loc = 0;
    for (char val: in)
    {
        if (newnum)
        {
            out.push_back(cnv[val]);
            newnum = false;
        }
        else
        {
            out [loc] <<= 4;
            out [loc] +=cnv[val];
            ++loc;
            newnum = true;
        }
    }
    return out;
}

这里有一个利用iostreams的优势:

std::vector<uint8_t> binarray2(const std::string & in)
{
    std::vector<uint8_t> out;
    std::stringstream cnv;
    bool newnum = true;

    for (char ch:in)
    {
        cnv << ch;
        if (newnum)
        {
            newnum = false;
        }
        else
        {
            cnv <<  ' ';
            newnum = true;
        }
    }

    int val;
    cnv >> std::hex;
    while (cnv >> val)
    {
        out.push_back(val);
    }
    return out;
}

请注意,它们都返回std::vector。您可以轻松地传递向量,它包含您需要的所有大小调整信息,并管理自己的内存。您可以使用std::vector::data来获取所需的字节数组。所有你需要做的就是保持向量,直到你完成字节数组,否则它将从你下面释放出数组。