将字符串转换为十六进制数组C ++

时间:2018-07-21 13:50:11

标签: c++

我有一个类似

的字符串
string test = "48656c6c6f20576f726c64"; 

,我想将其转换为

unsigned char state[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 
                           0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};

unsigned char bytearray[60];
int w;
for (w=0;w<str.length();w+2) {
    bytearray[w] = "0x" + str2[w];  
}

它似乎不起作用。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

请尝试以下类似操作:

_.uniqWith(_.flatten(arrays), _.isEqual);

或者:

#include <vector>
#include <string>

std::string test = "48656c6c6f20576f726c64"; 
size_t numbytes = test.size() / 2;

std::vector<unsigned char> bytearray;
bytearray.reserve(numbytes);

for (size_t w = 0, x = 0; w < numbytes; ++w, x += 2) {
    unsigned char b;

    char c = test[x];
    if ((c >= '0') && (c <= '9'))
        b = (c - '0');
    else if ((c >= 'A') && (c <= 'F'))
        b = 10 + (c - 'A');
    else if ((c >= 'a') && (c <= 'f'))
        b = 10 + (c - 'a');
    else {
        // error!
        break;
    }

    b <<= 4;

    c = test[x+1];
    if ((c >= '0') && (c <= '9'))
        b |= (c - '0');
    else if ((c >= 'A') && (c <= 'F'))
        b |= 10 + (c - 'A');
    else if ((c >= 'a') && (c <= 'f'))
        b |= 10 + (c - 'a');
    else {
        // error!
        break;
    }

    bytearray.push_back(b);
}

// use bytearray as needed...

Live Demo

答案 1 :(得分:-1)

在这里解释 C++ convert hex string to signed integer

做这样的事情:

unsigned int x;  
std::string substring; // you will need to figure out how to get this
std::stringstream ss;
ss << std::hex << substring;
ss >> x;

x是存储数组所需要的。 “ 48”实际上是您的字符串的已解析部分。在这里查看,因此您可能需要更改类型。玩吧。我也认为您在错误地解析您的字符串。检查一下Split string using loop to specific length sub-units