C ++ преобразует строку в шестнадцатеричное и наоборот - PullRequest
56 голосов
/ 01 августа 2010

Как лучше всего преобразовать строку в шестнадцатеричное и наоборот в C ++?

Пример:

  • Строка, подобная "Hello World", в шестнадцатеричный формат: 48656C6C6F20576F726C64
  • А из шестнадцатеричного 48656C6C6F20576F726C64 в строку: "Hello World"

Ответы [ 12 ]

0 голосов
/ 23 июля 2015

Это преобразует Hello World в 48656c6c6f20576f726c64 и print it.

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char hello[20]="Hello World";

    for(unsigned int i=0; i<strlen(hello); i++)
        cout << hex << (int) hello[i];
    return 0;
}
0 голосов
/ 12 августа 2012

Почему никто не использовал sprintf?

#include <string>
#include <stdio.h>

static const std::string str = "hello world!";

int main()
{
  //copy the data from the string to a char array
  char *strarr = new char[str.size()+1];
  strarr[str.size()+1] = 0; //set the null terminator
  memcpy(strarr, str.c_str(),str.size()); //memory copy to the char array

  printf(strarr);
  printf("\n\nHEX: ");

  //now print the data
  for(int i = 0; i < str.size()+1; i++)
  {
    char x = strarr[i];
    sprintf("%x ", reinterpret_cast<const char*>(x));
  }

  //DO NOT FORGET TO DELETE
  delete(strarr);

  return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...