From b3c8beb5c95f018d848a070efa83d8ac3e6b3340 Mon Sep 17 00:00:00 2001 From: Kutsan Kaplan Date: Tue, 12 Dec 2017 21:42:56 +0300 Subject: [PATCH] Update RGB to hexadecimal to new bitwise version --- snippets/RGB-to-hexadecimal.md | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/snippets/RGB-to-hexadecimal.md b/snippets/RGB-to-hexadecimal.md index c40fa2ff4..14da625c2 100644 --- a/snippets/RGB-to-hexadecimal.md +++ b/snippets/RGB-to-hexadecimal.md @@ -1,10 +1,22 @@ ### RGB to hexadecimal -Convert each value to a hexadecimal string, using `toString(16)`, then `padStart(2,'0')` to get a 2-digit hexadecimal value. -Combine values using `join('')`. +Convert given RGB parameters to hexadecimal string using bitwise left-shift operator. ```js const rgbToHex = (r, g, b) => - [r,g,b].map( v => v.toString(16).padStart(2,'0')).join(''); -// rgbToHex(0, 127, 255) -> '007fff' + ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); +// rgbToHex(255, 165, 1) -> 'ffa501' ``` + +Think the RGB values as binary, the max value for each will be `255` in decimal and `11111111` (8-bit) in binary. So, the left most side in hexadecimal form is for red value, middle part is green, most right side is blue, as you probably already know. To summarize it over orange `rgb(255, 165, 1)`, `#ffa501` color. + +``` + 255 165 1 + (r << 16) 11111111 00000000 00000000 ++ (g << 8) 11111111 10100101 00000000 ++ (b) 11111111 10100101 00000001 + +toString(16) ff a5 01 +``` + +We simply moving values to their appropriate locations. `padStart(6, '0')` is needed for leading left most zero characters.