如何转换十六进制字符串成char在C / C十六进制的数组++ [英] How to convert hex string to char array of hex in C/C++

查看:907
本文介绍了如何转换十六进制字符串成char在C / C十六进制的数组++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须用空格分隔十六进制值的字符串。

I have a string of hex values separated by white spaces.

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

需要阅读这并存储在unsigned char型数组..​​.

need to read this and store in unsigned char array...

有些东西像下面。

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

我坚持这个..可有人请帮助..

I am stuck with this .. can some one please help ..

情景:

我的实际情况是我写的AES 256 CBC加密/解密program.Where加密和解密的作品是孤立的。我们正计划在配置文件(键,值)加密,以DB密码从明文进行加密。 SO,独立的加密二进制文件将产生一个十六进制equivalant。因此,我们可以单独加密所有必要attribs并在写入配置文件。但是,在运行时,应用程序应该解密这些CONFIGS和用于连接到数据库等,所以我就在这种情况下阅读十六进制字符串和字符数组发送到AES dcrypt

My actual scenario is I am writing AES 256 CBC encryption/decryption program.Where encryption and decryption pieces are isolated. we are planning to encrypt DB passwords from clear text to encrypted in config files(key, value). SO, standalone encryption binary will produce a hex equivalant. So we can encrypt all necessary attribs separately and write them in to config file. But the application at run time should decrypt those configs and use to connect to db etc,so I got in to this situation of reading hex string and send it as char array to AES dcrypt

推荐答案

下面是一个例子:

#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;
}

这篇关于如何转换十六进制字符串成char在C / C十六进制的数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆