比较存储在std :: string中的数据字节

问题描述 投票:0回答:2

希望我能对此做足够合理的解释。

我有一个字符串,它是图像文件的十六进制表示形式。数据来自网络流,然后被写入文件,但是在通过write()写入文件之前,数据存储在字符串中,例如:

std::string mystr = "ffd8ffe000104a464946043c87b6e...21451457af4e2b91686e92b1ffd9";

现在,实际的字符串实际上实际上是10k个字符,但是重要的信息是开头的ffd8和结尾的ffd9。是的,是JPEG,但数据也可以是PNG或GIF。

我需要怎么做才能将字符串转换为可用的东西,以便进行类似的比较

if (mystr[0] == '\xff' && mystr[1] == '\xd8') {
   ..
}

很明显,因为mystr[0]是'f',所以我无法以这种方式索引到字符串对象吗?

我是否需要将字符串转换为各种字节数组?字节向量?

最终,我希望将x长度匹配到一系列字节,例如将上述字符串与89504E470D0A1A0A(PNG)匹配。

c++
2个回答
0
投票

(假设输入始终有效)

定义一个小型实用程序,将char转换为其十六进制解释。

inline uint8_t char_to_hex(char c)
{
  if(c <= '9') { return static_cast<uint8_t>(c - '0');
  } else if (c <= 'Z') {
    return static_cast<uint8_t>(10 + c - 'A');
  } else {
    return static_cast<uint8_t>(10 + c - 'a');
  }
}

然后您可以编写自己的函数以提取给定索引处的字节。

uint8_t at_index(std::string const& str, std::size_t index)
{
  std::size_t real_index = index * 2;

  char lhs = str[real_index];
  char rhs = str[real_index + 1];

  return (char_to_hex(lhs) << 4) | char_to_hex(rhs);
}

如上所述,您也可以将字符串转换为字节向量。

std::vector<uint8_t> to_hex_vec(std::string foo)
{
  std::vector<uint8_t> res(foo.size() / 2);

  for(std::size_t i = 0; i < foo.size(); i += 2)
  {
    res[i / 2] = (char_to_hex(foo[i]) << 4) | char_to_hex(foo[i + 1]);
  }

  return res;
}

0
投票

这是一个简单的函数,它:

1]假定字符串仅由字符0-9,a-f组成。

2)字符串中的字符数为偶数。

3)字节0是最高有效字节(最左侧)。如果需要相反的调整此选项。

4)没有边界/错误检查。

注意,这是执行此操作的许多方法之一,而不是“最佳”或最快方法的说明(可能是查找表的速度更快):

#include <cstring>
#include <string>
#include <iostream>

class StringToHexByte
{
    std::string str;

    char getByteValue(unsigned whichByte) const
    {
       static const char *digits="0123456789abcdef";
       char digit1 = strchr(digits, str[whichByte * 2]) - digits;
       char digit2 = strchr(digits, str[whichByte * 2 + 1]) - digits;
       return (digit1 << 4) | digit2;
    }

    public:
        StringToHexByte(const char *s) : str(s) {}

        char operator[] (unsigned idx) const
        { return getByteValue(idx); }
};

int main()
{
    StringToHexByte stoh("ff89d8");
    char byteValue0 = stoh[0];
    char byteValue1 = stoh[1];
    char byteValue2 = stoh[2];
    if ( byteValue0 == '\xff')
       std::cout << "We got the value of hex ff\n";
    if ( byteValue1 == '\x89')
       std::cout << "We got the value of hex 89\n";
    if ( byteValue2 == '\xd8')
       std::cout << "We got the value of hex d8";
}

输出:

We got the value of hex ff
We got the value of hex 89
We got the value of hex d8
© www.soinside.com 2019 - 2024. All rights reserved.