Как сравнить "4A4B4C" (строка показывает шестнадцатеричное значение) фактическая строка "JKL" - PullRequest
0 голосов
/ 02 июня 2011

Я получаю строку "4A4B4C4D4E4F" .. она равна строке ("JKLMNO")

Как проверить этот тип строки в c ++ .. (одна строка показывает шестнадцатеричное представление другой)

шестнадцатеричное значение

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

Ответы [ 3 ]

2 голосов
/ 02 июня 2011
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] = '\0'; //  null-terminate
    for (int i = 0; i < len; i++)
    {
        sprintf(hexed_string, "%X", string[i]);
        hexed_string += 2;
    }
    hexed_string -= 2*len;
    printf("%s\n", hexed_string);
    int res = strcmp(hexed_string, hex_string);
    delete hexed_string;
    return res;
}

if(!hexcmp("JKLMNO", "4A4B4C4D4E4F"))
    printf("Equal\n");
else
    printf("Nonequal\n");
2 голосов
/ 02 июня 2011

В качестве альтернативы это можно сделать с использованием строк и функций 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;
}
1 голос
/ 02 июня 2011

Одним из способов является преобразование каждых двух шестнадцатеричных цифр из вашей шестнадцатеричной строки и преобразование ее в десятичное значение, а затем сравнение этого преобразованного числа со значением 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] = '\0';
    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;
}
...