1

I have an array of hexadecimals and I need to convert it to string.

my array:

// declaration
unsigned char HEX_bufferMessage[12];

// initialize
    HEX_bufferMessage[0] = 0xF0;
    HEX_bufferMessage[1] = 0x15;
    HEX_bufferMessage[2] = 0x31;
    HEX_bufferMessage[3] = 0x02;
    HEX_bufferMessage[4] = 0x03;
    HEX_bufferMessage[5] = 0x00;
    HEX_bufferMessage[6] = 0x00;
    HEX_bufferMessage[7] = 0xD1;
    HEX_bufferMessage[8] = 0xD1;
    HEX_bufferMessage[9] = 0x00;
    HEX_bufferMessage[10] = 0x00;
    HEX_bufferMessage[11] = 0xF7;

I only have these informations in hexadecimal format, I need to convert them to string. Anyone know how I can do it??

Thank you!!

user2928858
  • 39
  • 1
  • 1
  • 5
  • 1
    Once again, `std::stringstream`. – thokra Nov 01 '13 at 11:42
  • 3
    Please note that `HEX_bufferMessage` is not "an array of hexadecimals", it's an array of `unsigned char`. Hexadecimal is just a *notation*, something used when representing a number externally. In memory, the numbers are stored in binary. You could do `HEX_bufferMessage[0] = 240;` and so on and have the exact same result in memory. – unwind Nov 01 '13 at 11:44

6 Answers6

3

Late to the party, but since all the answers using std::to_string() fail to output the hex values as hex values, I suggest you send them to a stream, where you can format your output via std::hex:

std::cout << "0x" << std::hex << HEX_bufferMessage[0] << std::endl;

or, if you want to use it in a string:

std::string to_hex_string( const unsigned int i ) {
    std::stringstream s;
    s << "0x" << std::hex << i;
    return s.str();
}

or even in a single line:

// ...
return (static_cast<std::stringstream const&>(std::stringstream() << "0x" << std::hex << i)).str();
Christian Severin
  • 1,793
  • 19
  • 38
2
std::bitset<16> foo(HEX_bufferMessage[0]);
std::string s = foo.to_string();

http://en.cppreference.com/w/cpp/utility/bitset/to_string

4pie0
  • 29,204
  • 9
  • 82
  • 118
1

something like this?

const char *hex = "0123456789ABCDEF";

unsigned char x = 0xF8;

std::cout << "0x" << hex[x >> 4 & 0xF] << hex[x & 0xF] << std::endl;
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
0

Use : std::to_string

for (size_t i =0 ; i<10; ++i)
{
   std::string s { std::to_string(HEX_bufferMessage[i]) }; //ith element
   std::cout << s; //concatenate all s as per need
}
P0W
  • 46,614
  • 9
  • 72
  • 119
0

How about std::to_string?

Like

std::string s;
for (auto const& v : HEX_bufferMessage)
    s += std::to_string(v);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0
char hex_string[12*2+1]; /* where 12 - is the number of you hex values, 2 - is 2 chars per each hex, and 1 is the final zero character */

for(int i=0;i<12;++i) {
  sprintf(hex_string+i*2,"%x", HEX_bufferMessage[i]);
}
CITBL
  • 1,587
  • 3
  • 21
  • 36