Convert RGB color to hex
Pack three 0–255 channels into a #rrggbb string.
function rgbToHex({ red, green, blue }) { return `#${((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1)}`; }
Input & expected output
Input
{
"red": 28,
"green": 97,
"blue": 65
}Expected output
"#1c6141"The edge case
Input
{
"red": 0,
"green": 0,
"blue": 0
}Expected output
"#000000"Know the limits
- The 1 << 24 term keeps leading zeros. Channels must be integers from 0 to 255.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Convert rgb color to hex from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Takes named channels and validates 0–255 integers. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Convert Celsius to Fahrenheit — Apply the temperature conversion without rounding the result.
- Convert hex to RGB — Expand #rgb if needed and read the red, green and blue channels.
- Convert URL parameters to object — Read a query string into an object; repeated keys become arrays.