Senin, 02 Juli 2012

Hex to RGB converter.


Quote
Converts a Hex string to RGB.

#include <iostream>
#include <string>
#include <sstream>

// RGB struct, with it's attributes: R, G and B.
struct RGB{
size_t R;
size_t G;
size_t B;
};
// Convert hexadecimal to decimal.
size_t hexToDec(const std::string &Hex)
{
std::istringstream istr(Hex);
size_t val;
// std::hex so the stringstream knows that
// we passed a hex.
istr >> std::hex >> val;
return val;
}
// Check for valid hex format.
bool isValidHex(const std::string &Hex)
{
// Allowed chars in the HEX string:
static const std::string allowedChars = "#0123456789abcdefABCDEF";
// The first character is #?
if (Hex[0] == '#')
{
  // Then the HEX string must have the length 7
  if (Hex.length() != 7)
   return false;
}
else
  // The first char is not #, then the HEX string
  // must have the length 6.
  if (Hex.length() != 6)
   return false;
// Check for non allowed chars:
if (Hex.find_first_not_of(allowedChars) != Hex.npos)
  return false;
return true;
}
RGB hexToRGB(std::string Hex)
{
if (!isValidHex(Hex))
  throw ((const std::string)"Received a non-valid hex string!\n");
// Remove # if present.
if (Hex[0] == '#')
  Hex.erase(Hex.begin());
// R = the substring with character 0 and 1.
std::string R = Hex.substr(0, 2);
// G = the substring with character 2 and 3.
std::string G = Hex.substr(2, 2);
// B = the substring with character 4 and 5.
std::string B = Hex.substr(4, 2);
RGB temp;
temp.R = hexToDec(R);
temp.G = hexToDec(G);
temp.B = hexToDec(B);
return temp;
}
// test
int main()
{
try
{
  RGB myRGB = hexToRGB("34cfff");
  // 34cfff to rgb is 52, 207, 255
  std::cout << "34cfff -> RGB(" << myRGB.R << ", " << myRGB.G << ", " << myRGB.B << ")\n";
}
catch (const std::string &e)
{
  std::cout << e << std::endl;
}
return 0;
}

Tidak ada komentar:

Posting Komentar