繁体   English   中英

C++ 如何将十六进制字符串 append 转换为字节数组?

[英]C++ How do I append the hexstring to the byte array?

我有个问题想了很久。

append 是否可以像 C++ 中那样将十六进制字符串转换为字节数组?

例子:

string hexString = "0x30";

我想将 append 转换为这样的字节数组或向量。

static const unsigned char example[] = {
   0x30
}

我怎样才能做到这一点?

您可以使用以下内容。 istringstream允许您从字符串中读取。 hex让您读取十六进制。

#include <iostream>
#include <sstream>

using namespace std;

string hexString = "0x30";

static unsigned char example[16] = {0};

int main()
{
    int pos = 0;
    istringstream iss(hexString);

    int x;
    while(iss >> hex >> x)
    {
        cout << x << std::endl;
        example[pos++] = x;
    }
}

使用stringstreamstd::hex 看看这个例子,稍后只需在数组中添加(char)x即可。

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    string hexString = "0x30";
    unsigned int x;   
    
    stringstream ss;
    ss << hex << hexString;
    ss >> x;
    
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM