diff --git a/README.md b/README.md index edad506c2..659880b74 100644 --- a/README.md +++ b/README.md @@ -395,13 +395,11 @@ const reverseString = str => [...str].reverse().join(''); ### 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 (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value. ```js -const rgbToHex = (r, g, b) => - [r,g,b].map( v => v.toString(16).padStart(2,'0')).join(''); -// rgbToHex(0, 127, 255) -> '007fff' +const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); +// rgbToHex(255, 165, 1) -> 'ffa501' ``` ### Scroll to top diff --git a/snippets/RGB-to-hexadecimal.md b/snippets/RGB-to-hexadecimal.md index 14da625c2..2b29c9d2a 100644 --- a/snippets/RGB-to-hexadecimal.md +++ b/snippets/RGB-to-hexadecimal.md @@ -1,22 +1,8 @@ ### RGB to hexadecimal -Convert given RGB parameters to hexadecimal string using bitwise left-shift operator. +Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value. ```js -const rgbToHex = (r, g, b) => - ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); +const rgbToHex = (r, g, b) => ((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.