Convert the given RGB color code to Hex color code | C ++ code to convert the given RGB color code to Hex color code ; function to convert decimal to hexadecimal ; char array to store hexadecimal number ; counter for hexadecimal number array ; temporary variable to store remainder ; storing remainder in temp variable . ; check if temp < 10 ; Return the equivalent hexadecimal color code ; Function to convert the RGB code to Hex color code ; The hex color code doesn 't exist ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; string decToHexa ( int n ) { char hexaDeciNum [ 2 ] ; int i = 0 ; while ( n != 0 ) { int temp = 0 ; temp = n % 16 ; 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 hexCode ; } 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 ; } else return " - 1" ; } 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 ; }