c++ - 将 unsigned char[] 解析为 std::string

标签 c++ casting byte ascii

我在解析 char[] 的内容时遇到问题。它包含字节,可以格式化为 ASCII 字符串。然而,最后两个字节是 CRC。因此,我将数组中除最后两个条目之外的所有内容都以十六进制解释为字符串:

std::ostringstream payload;
std::ostringstream crc;
payload << std::hex;
crc << std::hex;

// last two bytes are CRC
for (int i = 0; i < this->d_packetlen - 2; i++)
  {
  payload << static_cast<unsigned>(this->d_packet[i]);

     for (int j = i; j < this->d_packetlen; i++)
       {
         crc << static_cast<unsigned>(this->d_packet[j]);
       }
}
std::string payload_result = payload.str();
std::string crc_result = crc.str();

fprintf(d_new_fp, "%s, %s, %d, %d\n", payload_result.c_str(),
   crc_result.c_str(), this->d_lqi, this->d_lqi_sample_count);

这行不通,我不确定这是为什么?有没有更简单的方法将未签名的字符转换为 ASCII?

最好的, 马吕斯

最佳答案

这是一个无限循环:

for (int j = i; j < this->d_packetlen; i++)
{
   crc << static_cast<unsigned>(this->d_packet[j]);
}

在这个循环中,您不会递增j;相反,您正在递增 i。也许,这就是问题所在?


此外,根据您描述问题的方式,我认为正确的解决方案是:

for (int i = 0; i < this->d_packetlen - 2; i++)
{
  payload << static_cast<unsigned int>(this->d_packet[i]);
}
for (int j = this->d_packetlen - 2; j < this->d_packetlen; j++)
{
   crc << static_cast<unsigned int>(this->d_packet[j]);
}

也就是说,第二个循环应该在第一个循环之外。

关于c++ - 将 unsigned char[] 解析为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10895714/

相关文章:

c++ - 当 JSON 中存在非法字符时,如何防止 JSON 解析器崩溃?

c++嵌套策略模式,纯虚拟错误

c++ - 访问者模式通用应用的接口(interface)类

C++ 在声明为 void 类型后转换一个 int?

c++ - 如何使用 mpicc 和 cmake 更改 c++ 编译器

c# - 类型转换为具有相同属性的另一个

postgresql - 如何在 Postgresql 中将地球数据类型转换为 json

delphi - 逐位读取字节 - 简化/加速建议 - Delphi

java - java中有没有办法显示ASCII符号?

java - JAVA中String到byte[]和byte[]到String的相互转换