user2928858
user2928858

Reputation: 39

How can to convert hexadecimal to string? C++

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!!

Upvotes: 1

Views: 26867

Answers (6)

Christian Severin
Christian Severin

Reputation: 1831

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();

Upvotes: 3

CITBL
CITBL

Reputation: 1677

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

Upvotes: 0

4pie0
4pie0

Reputation: 29724

std::bitset<16> foo(HEX_bufferMessage[0]);
std::string s = foo.to_string();

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

Upvotes: 2

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

something like this?

const char *hex = "0123456789ABCDEF";

unsigned char x = 0xF8;

std::cout << "0x" << hex[x >> 4 & 0xF] << hex[x & 0xF] << std::endl;

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409136

How about std::to_string?

Like

std::string s;
for (auto const& v : HEX_bufferMessage)
    s += std::to_string(v);

Upvotes: 0

P0W
P0W

Reputation: 47784

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
}

Upvotes: 0

Related Questions