Step 1: Understand RGB color and hex color
- RGB means Red, Green, Blue color .RGB is an additive color model where different intensities of red,green and blue light combine to create a wide range of color.
- Hexadecimal (hex) means 16 number system. Hexadecimal number is used to represent colors. Hex code consist of a pound sign(#) followed by six alphanumeric character.
Step 2: Determine RGB color value
- RGB color value range from 0 to 255 representing the intensity of the respective color channel.
Step 3:Convert Hex to RGB.
- Divide each RGB value by 16 and note down the quotient and remainder.
- Convert the quotient and remainder into their corresponding hex value using the conversion table (0-9 and A-F).
- Concatenate the resulting hex values together,ensuring that each component is represented by characters.
- prefix the hex code with a pound sign(#) to indicate it is a hexadecimal color.
Example:- Converting RGB (255 , 0, 128) to hex .
- Red (255): 255divided by 6equals 15 with a remainder of 15(F in hex).
- Green(0): 0 divided by 16 equals 0 with a remainder of 0(0 in hex).
- Blue(128): 128 divided by 16 equals 8 with a remainder of 0 (8 in hex).
- Concatenating the hex color values:#FF08.
Code:-
def rgb_to_hex(r,g,b): return f"#{r:02x}{g:02x}{b:02x}" hex_color = rgb_to_hex(245,0,126) print(hex_color)
Output:-
#f5007e