首页 > 解决方案 > 将字符串转换为十六进制数组 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];  
}

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

标签: c++

解决方案


尝试更多类似的东西:

#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...

或者:

#include <vector>
#include <string>
#include <iomanip>

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)
{
    std::istringstream iss(test.substr(x, 2));
    unsigned short b;

    if (!(iss >> std::hex >> b)) {
        // error!
        break;
    }

    bytearray.push_back(static_cast<unsigned char>(b));
}

// use bytearray as needed...

现场演示


推荐阅读