From bf3ee6c00a206f8daf63cdde6aa6a6f9e0547a0e Mon Sep 17 00:00:00 2001 From: Kutsan Kaplan Date: Sun, 17 Dec 2017 09:14:05 +0300 Subject: [PATCH] Update Hexcode to RGB function with bitwise version --- snippets/hexcode-to-RGB.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/snippets/hexcode-to-RGB.md b/snippets/hexcode-to-RGB.md index 852a25ff8..2bb33480f 100644 --- a/snippets/hexcode-to-RGB.md +++ b/snippets/hexcode-to-RGB.md @@ -1,8 +1,11 @@ ### Hexcode to RGB -Use `Array.slice()`, `Array.map()` and `match()` to convert a hexadecimal colorcode (prefixed with `#`) to a string with the RGB values. +Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (prefixed with `#`) to a string with the RGB values. ```js -const hexToRgb = hex => `rgb(${hex.slice(1).match(/.{2}/g).map(x => parseInt(x, 16)).join()})` -// hexToRgb('#27ae60') -> 'rgb(39,174,96)' +const hexToRgb = hex => { + const h = parseInt(hex.slice(1), 16); + return `rgb(${h >> 16}, ${(h & 0x00ff00) >> 8}, ${h & 0x0000ff})`; +} +// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)' ```