Convert RGB to Hex color code in C++

We are going to code for conversion of RGB i.e red green blue color code to hex code in C++.

RGB to Hex color code in C++

RGB i.e. red, green and blue each contain 8 bits each with the integral value from 0 to 255 giving the intensity value of the color. The RGB input devices are used in various electronic devices like TV, video game, camera and digital camera etc. With the combination of these, we can make different colors codes.

We can convert RGB value to hex values by using a function

 std::string rgb2hex(int r, int g, int b, bool with_head) 
{ std::stringstream ss; 
if (with_head) 
ss << "#"; 
ss << std::hex << (r << 16 | g << 8 | b ); 
return ss.str();
 }

C++ code for conversion RGB to Hex color code

#include<iostream>
#include <sstream>

std::string rgb2hex(int r, int g, int b, bool with_head)
{
  std::stringstream ss;
  if (with_head)
    ss << "#";
  ss << std::hex << (r << 16 | g << 8 | b );
  return ss.str();
}
int main()
{
    int r,g,b;
    std::cout<<"Enter the value of RGB(from range 0 to 255):";
    std::cin>>r>>g>>b;
    std::cout<<rgb2hex(r,b,g,true)<<std::endl;
    return 0;
}


 

First, we input the value of RBG under range from 0-255. Then we can convert it into the hex color code.

Output:

Enter the value of RGB(from range 0 to 255):192 192 192
#c0c0c0

This shows the conversion of RGB to hex code.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *