A Y
A Y

Reputation: 177

Converting double rgba color values to character of hex

I have an array of doubles with rgba color values. Something like this:

double* colorVals = new double[4];
colorVals[0] = 0; 
colorVals[1] = 129;
colorVals[2] = 255;
colorVals[3] = .4;

I want to convert it to a string with Hex that contains something like this: "#0081FF"

How would I do this conversion?

Upvotes: 3

Views: 1640

Answers (2)

Roland Illig
Roland Illig

Reputation: 41686

if you know that the values are in range, you can use this code:

#include <string>
#include <cstring>

std::string rgbstr(const double *rgb) {
  char tmp[8];

  std::snprintf(tmp, sizeof(tmp), "#%02x%02x%02x", int(rgb[0]), int(rgb[1]), int(rgb[2]));
  return std::string(tmp);
}

Upvotes: 2

Mosi
Mosi

Reputation: 1258

You have to convert each double to hex that will be two character and then join all of them to a single string Note: see this to see how to convert double to hex

Upvotes: 0

Related Questions