簡體   English   中英

比較存儲在 std::string 中的數據的字節數

[英]Compare Bytes From Data Stored in a std::string

希望我能足夠合理地解釋這一點。

我有一個字符串,它是圖像文件的十六進制表示。 數據來自網絡 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ,然后被寫入文件,但在通過write()寫入文件之前,它存儲在如下字符串中:

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

當然,現在真正的字符串實際上是 10k 個字符,但重要的信息是開頭的ffd8和結尾的ffd9 是的 JPEG,但數據也可以是 PNG 或 GIF。

我需要做什么才能將字符串轉換為可用的東西,以便我可以進行比較

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

顯然,我不能那樣索引到字符串 object 因為mystr[0]是 'f' 對嗎?

我是否需要將字符串轉換為各種字節數組? 字節向量?

最終,我希望將 x 長度與一系列字節進行匹配,例如將上述字符串與89504E470D0A1A0A (PNG) 進行匹配。

(假設輸入始終有效)

定義一個小實用程序來將 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');
  }
}

然后您可以編寫自己的 function 來提取給定索引處的字節。

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

這是一個簡單的 function :

1) 假設字符串僅由字符 0-9、af 組成。

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";
}

Output:

We got the value of hex ff
We got the value of hex 89
We got the value of hex d8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM