如何比较"4A4B4C"(字符串显示十六进制值)实际字符串"JKL"

How to compare "4A4B4C" (string shows hex value) actual string is "JKL"

本文关键字:字符串 JKL 十六进制 4A4B4C 何比较 比较 显示      更新时间:2023-10-16

我得到一个字符串"4A4B4C4D4E4F"。。它等于字符串("JKLMNO"

我如何在c++中检查这种类型的字符串。。(一个字符串显示另一个字符串的十六进制表示)

的十六进制值

J=4A, K=4B, L=4C

或者,这可以使用C++字符串和特性而不是C样式字符串来完成:

#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <iomanip>
#include <string>
bool compareAscii(const std::string& string, const std::string& asciistr) {
   std::ostringstream result;
   result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
   // We copy the contents of string, using the range from the beginning to the end.
   // By copying it to an ostream iterator it gets written to the ostringstream,
   // but crucially we treat it as an unsigned int when we write it, which causes
   // the chars to get printed as their numerical values instead.
   std::copy(string.begin(), string.end(), std::ostream_iterator<unsigned int>(result));
   return result.str() == asciistr;
}
namespace {
   const std::string test="JKLMNO";
   const std::string value="4A4B4C4D4E4F";
}
int main() {
   std::cout << "compareAscii("" << test << "", "" << value << "") returned " << compareAscii(test, value) << std::endl;
   return 0;
}
int hexcmp(const char *string, const char *hex_string)
{
    int len = strlen(string);
    char *hexed_string = new char[2*len+1];
    hexed_string[2*len] = ''; //  null-terminate
    for (int i = 0; i < len; i++)
    {
        sprintf(hexed_string, "%X", string[i]);
        hexed_string += 2;
    }
    hexed_string -= 2*len;
    printf("%sn", hexed_string);
    int res = strcmp(hexed_string, hex_string);
    delete hexed_string;
    return res;
}
if(!hexcmp("JKLMNO", "4A4B4C4D4E4F"))
    printf("Equaln");
else
    printf("Nonequaln");

一种方法是将十六进制字符串中的每两个十六进制数字转换为十进制值,然后将转换后的数字与要比较的字符串的ASCII值进行比较。

示例代码如下所示:

int main (void)
{
  char str1[]="4A4B4C4D4E4F";
  char str2[]="JKLMNO";
  char buffer[3];
  int n, i = 0, j = 0, value, flag = 1;
  n = strlen (str1);
  while (i<n)
  {
    buffer[0] = str1[i++];
    buffer[1] = str1[i++];
    buffer[2] = '';
    value = strtol (buffer, NULL, 16);
    if (str2[j] != value)
    {
      flag = 0;
      break;
    }
    j++;
  }
  if (flag)
    printf ("nMatch");
  else
    printf ("nNo Match");
  printf ("n");
  reutrn 0;
}