Daniel Lara
Daniel Lara

Reputation: 52

C++ converting vector to 2 hex and then store it in a string

I have been using mostly C so I am pretty new into c++. I want to convert a int vector (std::vector) into hexadecimal representation and then store that into a string. I found something I would use in C in the following thread: Converting hex into a string using 'sprintf'

The code proposed by user411313 is the following:

static unsigned char  digest[16];
static unsigned char hex_tmp[16];

for (i = 0; i < 16; i++) {
  printf("%02x",digest[i]);  
  sprintf(&hex_tmp[i], "%02x", digest[i]);  
}

One of my concerns is that this could go out of index at some point since sprintf may try to add a 0 after the content. Also, I was wondering if there is any way to do it with native C++, perhaps any built function could be used instead of C functions. Is this preferable in c++ over c functions? Thank you very much for your assistance!

Upvotes: 0

Views: 2835

Answers (2)

user0042
user0042

Reputation: 8018

if there is any way to do it with native C++, perhaps any built function could be used instead of C functions. Is this preferable in c++ over c functions?

Sure there is a way, and yes it's preferable:

static std::array<unsigned char,16> digest;
static std::string hex_tmp;

for (auto x : digest) {
    std::ostringstream oss;
    oss << std::hex << std::setw(2) << std::setfill('0') << (unsigned)x;
    hex_tmp += oss.str();
}

One of my concerns is that this could go out of index at some point since sprintf may try to add a 0 after the content.

That's a valid concern. The classes used in my code snippet above will overcome all these issues, and you don't need to care about.

Upvotes: 2

BiagioF
BiagioF

Reputation: 9705

You can use std::stringstream

std::string hex_representation(const std::vector<int>& v) {
  std::stringstream stream;
  for (const auto num : v) {
    stream << "0x" << std::hex << std::setw(2) << std::setfill('0') << num
           << ' ';
  }
  return stream.str();
}

Obviously you can remove the "0x" prefix if you don't need it

Here a live demo.

Upvotes: 0

Related Questions