Update RGB to Hex, build README

This commit is contained in:
Angelos Chalaris
2017-12-12 20:54:57 +02:00
parent 6f6e6d2289
commit 52bb235344
2 changed files with 5 additions and 21 deletions

View File

@ -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

View File

@ -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.