从"常量字符*"转换为"字节"

conversion from `const char*' to `byte'

本文关键字:字节 转换 字符 常量      更新时间:2023-10-16

我在将常量字符转换为字节时遇到问题。我使用ifstream读取文件,它以字符串形式提供内容,然后我使用c_str()将字符串转换为const-char;然后尝试将其插入到字节数组中以用于数据包发送目的。我是c++的新手,不明白如何将字符转换为字节,需要你们的帮助。这是我的代码,请给我一些建议

byte buf[42];
const char* fname = path.c_str();
ifstream inFile;
inFile.open(fname);//open the input file
stringstream strStream;
strStream << inFile.rdbuf();//read the file
string str = strStream.str();//str holds the content of the file
vector<string> result = explode(str,',');
for (size_t i = 0; i < result.size(); i++) {
    buf[i] = result[i].c_str(); // Here is Error
    cout << """ << result[i] << """ << endl;
}
system("pause");

这是我从文件中获取的数据:(0x68,0x32,0x01,0x7B,0x01,0x1F,0x00,0x00,0x00,0x02,0x00,0x0,0x00,0x00)

您正试图将字符串(多个字符)分配给单个字节。它不合身。试试之类的东西

在循环开始前添加:

size_t bufpos = 0;

然后在环路内

const string & str = resulti[i];
for (size_t strpos = 0; strpos < str.size() && bufpos < sizeof(buf); ++strpos)
{
   buf[bufpos++] = str[strpos];
}

我自己做的,现在我将解释解决方案。所以我想要String(0x68,0x32,0x03,0x22等)变量按照","进行拆分,然后将其转换为十六进制值,所有这些都将其作为16位十六进制值输入到字节数组中。

char buf[42]; // Define Packet
const char* fname = path.c_str(); // File Location

ifstream inFile; //
inFile.open(fname);//open the input file
stringstream strStream;
strStream << inFile.rdbuf();//read the file
string str = strStream.str();//str holds the content of the file

vector<string> result = explode(str,','); // Explode Per comma

for (size_t i = 0; i < result.size(); i++) { // loop for every exploded value
unsigned int x;   
std::stringstream ss;
ss << std::hex <<  result[i];    // Convert String Into Integer value 
ss >> x;
buf[i] = x;
 printf(&buf[i],"%04x",x); //Convert integer value back to 16 bit hex value and store into array

    }

  system("pause");

感谢大家的重播。