gpt4 book ai didi

C 字符串大小和数组

转载 作者:行者123 更新时间:2023-11-30 21:47:12 25 4
gpt4 key购买 nike

我遇到了一个问题。我有以下示例

std::string key = "30 14 06 03 55 04 03 14 0D 2A";

当我找到 key 字符串的大小

 size_t sizee = key.size();

结果是 29,没问题。

但我想要这样的输出

char data[10];
data[0] = 0x30;
data[1] = 0x14;
data[2] = 0x06;
data[3] = 0x03;
data[4] = 0x55;
data[5] = 0x04;
data[6] = 0x03;
data[7] = 0x14;
data[8] = 0x0D;
data[9] = 0x2A;

考虑到 30 为一个,14 为两个,大小应为 10。这个大小应该是数组的大小,就好像字符串变成 00 01 数组大小应该是 2。

最佳答案

#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>
using namespace std;

int main(){
string key = "30 14 06 03 55 04 03 14 0D 2A";
istringstream iss(key);
vector<char> data;
unsigned x;
iss >> hex;
while(iss >> x){
data.push_back(x);
}
size_t size = data.size();
cout << "char data[" << size << "];" << endl;
for(int i=0;i < size ; ++i){
cout << "data[" << i << "] = 0x"
<< hex << uppercase << setw(2) << setfill('0') << (unsigned)data[i] << ';' << endl;
}
}
<小时/>
#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>
#include <cstdlib>
using namespace std;

int main(){
string key = "30 14 06 03 55 04 03 14 0D 2A";
istringstream iss(key);
vector<char> data;
unsigned x;
iss >> hex;
while(iss >> x){
data.push_back(x);
}
size_t size = data.size();
cout << "char content[" << size << "];" << endl;
unsigned *content;
content = (unsigned*)malloc(size*sizeof(unsigned));
for(int i=0;i < size ; ++i){
//cout << "data[" << i << "] = 0x" << hex << uppercase << setw(2) << setfill('0') << (unsigned)data[i] << endl;
content[i]=data[i];
cout << "content[" << i << "] = 0x" << hex << uppercase << setw(2) << setfill('0') << content[i] << endl;
}
if(content[0] == 0x30)
cout << "I get it." << endl;
free(content);
}

关于C 字符串大小和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22485956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com