如何在C / C ++中将十六进制字符串转换为十六进制的char数组

时间:2014-10-16 18:31:30

标签: c++ arrays string char hex

我有一串以white spaces分隔的十六进制值。

std::string hexString = "0x60 0xC7 0x80" and so on...

我需要阅读此内容并存储在unsigned char数组中:

unsigned char array[] = {0x60, 0xC7, 0x80}.

我坚持这个。有人可以帮忙吗?

情境:

我正在编写AES 256 CBC加密/解密程序。加密和解密部分是隔离的。我们计划使用(key,value)将数据库密码从明文加密到存储在配置文件中的加密密码。独立加密二进制文件将生成十六进制等效项。我们分别加密所有必要的属性并将它们写入配置文件。 运行时的应用程序应该对这些配置进行解密,以便将其用于连接到DB等。 我必须读取十六进制字符串并将其作为char数组发送到AES解密算法。

2 个答案:

答案 0 :(得分:0)

以下是一个例子:

#include <regex>
#include <string>
#include <iostream>

template <typename Iterator>
class iterator_pair {
    public:
        iterator_pair(Iterator first, Iterator last): f_(first), l_(last) {}
        Iterator begin() const { return f_; }
        Iterator end() const { return l_; }

    private:
        Iterator f_;
        Iterator l_;
};

template <typename Iterator>
iterator_pair<Iterator> make_iterator_pair(Iterator f, Iterator l) {
    return iterator_pair<Iterator>(f, l);
}

int main() {
    std::string hexString = "0x60 0xC7 0x80";
    std::regex whitespace("\\s+");
    std::vector<int> hexArray;

    auto tokens = make_iterator_pair(
            std::sregex_token_iterator(hexString.begin(), hexString.end(), whitespace, -1),
            std::sregex_token_iterator());

    for (auto token : tokens)
        hexArray.push_back(stoi(token, 0, 0));

    for (auto hex : hexArray)
        std::cout << hex << std::endl;
}

答案 1 :(得分:0)

  

我有std::string hexString ...我需要将其存储在unsigned char array[]

请查看以下基于strtoul功能的解决方案。 strtoul的输入字符串可能包含任意数量的空格和/或标签,可能后跟一个符号,后跟一串数字。 因此,即使是" 01 2 \t ab \t\t 3\n"之类的不完美输入也可以被正确解析。

功能:

unsigned char * create_hex_array (const std::string * str, size_t * nr_of_elements);

获取指向输入std::string hexString的指针,并返回unsigned char array以及数组中元素的数量。

#include <iostream>     // std::cout, std::endl
#include <sstream>      // std::stringstream
#include <iomanip>      // std::setfill, std::setw
#include <string>       // std::string
#include <cstring>      // functions to manipulate C strings and arrays

unsigned char * create_hex_array (const std::string * str, size_t * nr_of_elements)
{
    size_t index = 0;                       // elements counter       
    size_t arr_len = str->size () / 2 + 1;  // maximum number or array elements        
    const char *current = str->c_str ();    // start from the beginning of the string   
    char *end = NULL;                       // init the end pointer 
    unsigned char *arr = new unsigned char[arr_len]; // allocate memory for our array

    while (1)
    {
        unsigned long hex = strtoul (current, &end, 16);  
        if (current == end)                 // end of string reached
            break;
        arr[index] = (unsigned char) hex;   // store the hex number in the array 
        index++;                            // increase index to the next slot in array    
        current = end;                      // move the to next number
    }

    *nr_of_elements = index;                // return number of elements in the array             
    return arr;                             // return created array 
}

void print_hex_array (size_t size, unsigned char *arr)
{
    std::cout << "Nr of elements in the array is = " << size << std::endl;
    // Fancy print out:
    // Getting a buffer into a stringstream in hex representation with zero padding
    // with 0-padding on small values so  `5` would become `05`
    std::stringstream ss;
    ss << std::hex << std::setfill ('0');

    for (size_t i = 0; i < size; i++)
    {
        // In C this is enough:  printf("%02x ", arr[i]);
        ss << std::setw (2) << static_cast < unsigned >(arr[i]) << " ";
    }

    std::cout << ss.rdbuf() << std::endl;
}

int main ()
{
    const std::string hexString = " 5 8d  77 77 96 1 \t\t bc 95 b9 ab 9d 11 \n";  
    size_t arr_size;                    // Number of elements in the array

    unsigned char * array = create_hex_array (&hexString, &arr_size); 
    print_hex_array (arr_size, array);  // printout with 0- padding.

    delete[]array;                      // release memory
    return 0;
}

输出:

Nr of elements in the array is = 12                                                                                                                    
05 8d 77 77 96 01 bc 95 b9 ab 9d 11