从"常量字符*"转换为"字节"
conversion from `const char*' to `byte'
我在将常量字符转换为字节时遇到问题。我使用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");
感谢大家的重播。
相关文章:
- 如何在连接器 C++ 中将原始字节转换为字符串
- 将 char[] 数组转换为字节,然后将字节转换为 int,反之亦然
- 如何在 c++ 中将字节转换为 ASCII 十六进制表示形式?
- OPENSSL 将二进制字节转换为 SHA256 C++
- 如何将音频字节转换为样本
- C++ 如何将 char[] 中的多个字节转换为一个整数
- 删除字节转换的char*
- 如何将二进制字节转换为可打印的数值
- 将 MFRC522 UID 十六进制字节转换为可打印的小数
- 用c++将十六进制字符串切碎,并将中的每个字节转换为十进制
- Qt是否有一种将字节转换为int的方法,反之亦然
- UCS-4 到 Solaris 上的多字节转换
- 使用 C++ 将四个字节转换为整数
- 将字节转换为无符号整数的最快方法
- 如何在mac上将多字节转换为宽字符
- 将字节转换为整数
- 在Arduino错误时将4个字节转换为长字节
- 更正从C++到delphi AnsiString的字节转换
- 用C++将4个字节转换为3个字节
- 正在将字节转换为char数组,然后再转换回来