简体   繁体   English

将未签名的char []解析为std :: string

[英]Parse unsigned char[] to std::string

I have a problem with parsing the contents of a char[]. 我在解析char []的内容时遇到问题。 It contains bytes, that can be formated as ASCII stings. 它包含字节,可以将其格式化为ASCII字符串。 The last two bytes however are CRC. 但是,最后两个字节是CRC。 Therefore I interpret everything but the last two entries in the array in hex to string: 因此,我将十六进制中除数组中最后两个条目以外的所有内容解释为字符串:

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);

This doesn't work, and I'm not sure why that is? 这不起作用,我不确定为什么会这样吗? Is there an easier way to cast unsinged chars to ASCII? 有没有更简单的方法可以将不带字符的字符转换为ASCII?

Best, Marius 最好,马吕斯

This is an infinite loop: 这是一个无限循环:

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

In this loop, you are NOT incrementing j ; 在此循环中,您不会递增j instead you're incrementing i . 相反,您要增加i Maybe, that is the problem? 也许那是问题所在?


Also, the way you've described the problem, I think the correct solution is this: 另外,按照您描述问题的方式,我认为正确的解决方案是:

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]);
}

That is the second loop should be outside the first loop. 那就是第二个循环应该在第一个循环之外。

I think the problem is that your nested loop increments i instead of j . 我认为问题是嵌套循环将i而不是j递增。

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++ /* <=== HERE */)
     {
         crc << static_cast<unsigned>(this->d_packet[j]);
     }
}

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

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