Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rohitsharmaj7/33c52777b4d032b317752bd9ed65b220 to your computer and use it in GitHub Desktop.
Save rohitsharmaj7/33c52777b4d032b317752bd9ed65b220 to your computer and use it in GitHub Desktop.
LinkedIn Query
First of all let's clear the things we have used in this conversion
1. Why toString(16) only?
2. Role of 1<<24
3. Role of Slice function
Answer 1:
Hexadecimal is base 16.
Break down the words: hexa, meaning 6; decimal, meaning 10.
Therefore, 10 + 6 = 16 (So, as we are converting to hexadecimal, that's why we are using toString(16) method
Answer 2:
Now your main question comes into play, What << does?
<< is known as the left shift operator, when you write 1<<4 means we are adding 4 zeros at the last or right side shifting 1 to the left side i.e giving us the number in binary form 10000, now we convert this number to its various variants like Decimal, Octal, Hexa-Decimal versions
1<<4 in Binary is equals to 10000
1<<4 in Decimal is equals to 16
1<<4 in Hexadecimal equals to 10
1<<4 in Octal equals to 20
Similarly, 1<<24 looks like as shown below
1<<24 in Binary is equals to 1000000000000000000000000
1<<24 in Decimal is equals to 16777216
1<<24 in Hexadecimal equals to 1000000
1<<24 in Octal equals to 100000000
Let Clarify it more with an example
Suppose, r and g were both zero and b was 51
0<<16 gives 0
0<<8 gives 0
51
(0+0+51).toString(16) gives 33
If 1<<24 is not used, we will get #33 (which is not valid hexcolor), so that why, to give our hexcolorcode left padded
zeroes, whenever no value to r or g is assigned as we did in our example
1<<24 gives 1000000
adding 1 << 24 and we get "1000033".
Answer 3:
Now to remove the extra one added in 1000033 we used slice, So that we can get 000033, which finally gives us #000033 as per our return statement.
To verify go to any rgb to hex color conversion tool online and enter rgb(0,0,51) you will get #000033
@rohitsharmaj7
Copy link
Author

Answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment