Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
Convert the given RGB color code to Hex color code
Next article icon

Convert the given RGB color code to Hex color code

Last Updated : 17 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given three colors, such as R, G, and B, convert these RGB color to a hex color code. If the conversion is not possible, print -1.


Examples: 

Input: R = 0, G = 0, B = 0 
Output: #000000


Input: R = 255, G = 255, B = 256 
Output: -1 
Explanation: 
A 256 color code is not possible as only the 0-255 range is available for a color.  

Approach:

  1. First, check if each of the given colors is in the range 0-255 or not.
  2. If not, then print -1 and exit the program as no conversion is possible in this case.
  3. If they are in range, then for each color, convert the given color code into its equivalent hexadecimal number.
  4. If the hexadecimal value is 1 digit, add 0 to the left to make it 2 digits.
  5. Then, in the final answer, add '#' at the start, followed by the hexadecimal values of R, G, and B respectively.


Below is the implementation of the above approach. 

C++
// C++ code to convert the given RGB // color code to Hex color code  #include <iostream> using namespace std;  // function to convert decimal to hexadecimal string decToHexa(int n) {     // char array to store hexadecimal number     char hexaDeciNum[2];      // counter for hexadecimal number array     int i = 0;     while (n != 0) {          // temporary variable to store remainder         int temp = 0;          // storing remainder in temp variable.         temp = n % 16;          // check if temp < 10         if (temp < 10) {             hexaDeciNum[i] = temp + 48;             i++;         }         else {             hexaDeciNum[i] = temp + 55;             i++;         }          n = n / 16;     }      string hexCode = "";     if (i == 2) {         hexCode.push_back(hexaDeciNum[0]);         hexCode.push_back(hexaDeciNum[1]);     }     else if (i == 1) {         hexCode = "0";         hexCode.push_back(hexaDeciNum[0]);     }     else if (i == 0)         hexCode = "00";      // Return the equivalent     // hexadecimal color code     return hexCode; }  // Function to convert the // RGB code to Hex color code string convertRGBtoHex(int R, int G, int B) {     if ((R >= 0 && R <= 255)         && (G >= 0 && G <= 255)         && (B >= 0 && B <= 255)) {          string hexCode = "#";         hexCode += decToHexa(R);         hexCode += decToHexa(G);         hexCode += decToHexa(B);          return hexCode;     }      // The hex color code doesn't exist     else         return "-1"; }  // Driver program to test above function int main() {     int R = 0, G = 0, B = 0;     cout << convertRGBtoHex(R, G, B) << endl;      R = 255, G = 255, B = 255;     cout << convertRGBtoHex(R, G, B) << endl;      R = 25, G = 56, B = 123;     cout << convertRGBtoHex(R, G, B) << endl;      R = 2, G = 3, B = 4;     cout << convertRGBtoHex(R, G, B) << endl;      R = 255, G = 255, B = 256;     cout << convertRGBtoHex(R, G, B) << endl;      return 0; } 
Java
// Java code to convert the given RGB // color code to Hex color code    import java.util.*;  class GFG{   // function to convert decimal to hexadecimal static String decToHexa(int n) {     // char array to store hexadecimal number     char []hexaDeciNum = new char[2];       // counter for hexadecimal number array     int i = 0;     while (n != 0) {           // temporary variable to store remainder         int temp = 0;           // storing remainder in temp variable.         temp = n % 16;           // check if temp < 10         if (temp < 10) {             hexaDeciNum[i] = (char) (temp + 48);             i++;         }         else {             hexaDeciNum[i] = (char) (temp + 55);             i++;         }           n = n / 16;     }       String hexCode = "";     if (i == 2) {         hexCode+=hexaDeciNum[0];         hexCode+=hexaDeciNum[1];     }     else if (i == 1) {         hexCode = "0";         hexCode+=hexaDeciNum[0];     }     else if (i == 0)         hexCode = "00";       // Return the equivalent     // hexadecimal color code     return hexCode; }   // Function to convert the // RGB code to Hex color code static String convertRGBtoHex(int R, int G, int B) {     if ((R >= 0 && R <= 255)         && (G >= 0 && G <= 255)         && (B >= 0 && B <= 255)) {           String hexCode = "#";         hexCode += decToHexa(R);         hexCode += decToHexa(G);         hexCode += decToHexa(B);           return hexCode;     }       // The hex color code doesn't exist     else         return "-1"; }   // Driver program to test above function public static void main(String[] args) {     int R = 0, G = 0, B = 0;     System.out.print(convertRGBtoHex(R, G, B) +"\n");       R = 255; G = 255; B = 255;     System.out.print(convertRGBtoHex(R, G, B) +"\n");       R = 25; G = 56; B = 123;     System.out.print(convertRGBtoHex(R, G, B) +"\n");       R = 2; G = 3; B = 4;     System.out.print(convertRGBtoHex(R, G, B) +"\n");       R = 255; G = 255; B = 256;     System.out.print(convertRGBtoHex(R, G, B) +"\n");   } }  // This code is contributed by 29AjayKumar 
Python3
# Python3 program to convert the given  # RGB color code to Hex color code   # Function to convert decimal to hexadecimal  def decToHexa(n):       # char array to store hexadecimal number      hexaDeciNum = ['0'] * 100      # Counter for hexadecimal number array      i = 0          while (n != 0):           # Temporary variable to store remainder          temp = 0          # Storing remainder in temp variable.          temp = n % 16          # Check if temp < 10          if (temp < 10):              hexaDeciNum[i] = chr(temp + 48)             i = i + 1          else:              hexaDeciNum[i] = chr(temp + 55)             i = i + 1          n = int(n / 16)      hexCode = ""     if (i == 2):         hexCode = hexCode + hexaDeciNum[0]          hexCode = hexCode + hexaDeciNum[1]       elif (i == 1):          hexCode = "0"         hexCode = hexCode + hexaDeciNum[0]      elif (i == 0):         hexCode = "00"      # Return the equivalent      # hexadecimal color code      return hexCode  # Function to convert the  # RGB code to Hex color code  def convertRGBtoHex(R, G, B):       if ((R >= 0 and R <= 255) and         (G >= 0 and G <= 255) and         (B >= 0 and B <= 255)):           hexCode = "#";          hexCode = hexCode + decToHexa(R)         hexCode = hexCode + decToHexa(G)          hexCode = hexCode + decToHexa(B)          return hexCode      # The hex color code doesn't exist      else:         return "-1"  # Driver Code R = 0 G = 0 B = 0 print (convertRGBtoHex(R, G, B))   R = 255 G = 255 B = 255 print (convertRGBtoHex(R, G, B))  R = 25 G = 56 B = 123 print (convertRGBtoHex(R, G, B))  R = 2 G = 3 B = 4 print (convertRGBtoHex(R, G, B))  R = 255 G = 255 B = 256 print (convertRGBtoHex(R, G, B))  # This code is contributed by Pratik Basu  
C#
// C# code to convert the given RGB // color code to Hex color code using System;  class GFG{  // Function to convert decimal  // to hexadecimal static string decToHexa(int n) {          // char array to store      // hexadecimal number     char []hexaDeciNum = new char[2];      // Counter for hexadecimal      // number array     int i = 0;     while (n != 0)     {          // Temporary variable to         // store remainder         int temp = 0;          // Storing remainder in          // temp variable.         temp = n % 16;          // Check if temp < 10         if (temp < 10)          {             hexaDeciNum[i] = (char) (temp + 48);             i++;         }         else          {             hexaDeciNum[i] = (char) (temp + 55);             i++;         }         n = n / 16;     }     string hexCode = "";          if (i == 2)     {         hexCode += hexaDeciNum[0];         hexCode += hexaDeciNum[1];     }     else if (i == 1)     {         hexCode = "0";         hexCode += hexaDeciNum[0];     }     else if (i == 0)         hexCode = "00";      // Return the equivalent     // hexadecimal color code     return hexCode; }  // Function to convert the // RGB code to Hex color code static string convertRGBtoHex(int R, int G,                                      int B) {     if ((R >= 0 && R <= 255) &&          (G >= 0 && G <= 255) &&          (B >= 0 && B <= 255))      {         string hexCode = "#";         hexCode += decToHexa(R);         hexCode += decToHexa(G);         hexCode += decToHexa(B);          return hexCode;     }      // The hex color code doesn't exist     else         return "-1"; }  // Driver code public static void Main(string[] args) {     int R = 0, G = 0, B = 0;     Console.Write(convertRGBtoHex(R, G, B) + "\n");      R = 255; G = 255; B = 255;     Console.Write(convertRGBtoHex(R, G, B) + "\n");      R = 25; G = 56; B = 123;     Console.Write(convertRGBtoHex(R, G, B) + "\n");      R = 2; G = 3; B = 4;     Console.Write(convertRGBtoHex(R, G, B) + "\n");      R = 255; G = 255; B = 256;     Console.Write(convertRGBtoHex(R, G, B) + "\n"); } }  // This code is contributed by rutvik_56 
JavaScript
<script>  // Javascript code to convert the given RGB // color code to Hex color code  // function to convert decimal to hexadecimal function decToHexa(n) {     // char array to store hexadecimal number     let hexaDeciNum = Array.from({length: 2}, (_, i) => 0);         // counter for hexadecimal number array     let i = 0;     while (n != 0) {             // temporary variable to store remainder         let temp = 0;             // storing remainder in temp variable.         temp = n % 16;             // check if temp < 10         if (temp < 10) {             hexaDeciNum[i] = String.fromCharCode(temp + 48);             i++;         }         else {             hexaDeciNum[i] =  String.fromCharCode(temp + 55);             i++;         }             n = Math.floor(n / 16);     }         let hexCode = "";     if (i == 2) {         hexCode+=hexaDeciNum[0];         hexCode+=hexaDeciNum[1];     }     else if (i == 1) {         hexCode = "0";         hexCode+=hexaDeciNum[0];     }     else if (i == 0)         hexCode = "00";         // Return the equivalent     // hexadecimal color code     return hexCode; }     // Function to convert the // RGB code to Hex color code function convertRGBtoHex(R, G, B) {     if ((R >= 0 && R <= 255)         && (G >= 0 && G <= 255)         && (B >= 0 && B <= 255)) {             let hexCode = "#";         hexCode += decToHexa(R);         hexCode += decToHexa(G);         hexCode += decToHexa(B);             return hexCode;     }         // The hex color code doesn't exist     else         return "-1"; }   // Driver Code          let R = 0, G = 0, B = 0;     document.write(convertRGBtoHex(R, G, B) +"<br/>");         R = 255; G = 255; B = 255;     document.write(convertRGBtoHex(R, G, B) +"<br/>");         R = 25; G = 56; B = 123;     document.write(convertRGBtoHex(R, G, B) +"<br/>");         R = 2; G = 3; B = 4;     document.write(convertRGBtoHex(R, G, B) +"<br/>");         R = 255; G = 255; B = 256;     document.write(convertRGBtoHex(R, G, B) +"<br/>");                 </script> 

Output: 
#000000 #FFFFFF #9183B7 #020304 -1

 

Time Complexity: O(log16N)

Auxiliary Space: O(1)


Next Article
Convert the given RGB color code to Hex color code

C

code_r
Improve
Article Tags :
  • Pattern Searching
  • Mathematical
  • DSA
  • base-conversion
Practice Tags :
  • Mathematical
  • Pattern Searching

Similar Reads

    Check if the given RGB color code is valid or not
    Given three numbers R, G and B as the color code for Red, Green and Blue respectively as in the form of RGB color code. The task is to know whether the given color code is valid or not. RGB Format: The RGB(Red, Green, Blue) format is used to define the color of an HTML element by specifying the R, G
    10 min read
    Program to Change RGB color model to HSV color model
    Given RGB color range, our task is to convert RGB color to HSV color.RGB Color Model : The RGB color model is an additive color model in which red, green and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three
    9 min read
    Check if a given string is a valid Hexadecimal Color Code or not
    Given a string str, the task is to check whether the given string is an HTML Hex Color Code or not. Print Yes if it is, otherwise print No. Examples: Input: str = “#1AFFa1”Output: Yes Input: str = “#F00”Output: Yes Input: str = �”Output: No Approach: An HTML Hex Color Code follows the below-mentione
    7 min read
    How to validate Hexadecimal Color Code using Regular Expression
    Given string str, the task is to check whether the string is valid hexadecimal colour code or not by using Regular Expression. The valid hexadecimal color code must satisfy the following conditions. It should start from '#' symbol.It should be followed by the letters from a-f, A-F and/or digits from
    6 min read
    Program to Convert Hexadecimal to Octal
    Given a Hexadecimal number, the task is to convert it into an Octal number.Examples: Input: Hexadecimal = 1AC Output: Binary = 0654 Explanation: Equivalent binary value of 1: 0001 Equivalent binary value of A: 1010 Equivalent binary value of C: 1100 Grouping in terms of 3: 000 110 101 100 Equivalent
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences