Created
July 10, 2022 01:23
-
-
Save rohitsharmaj7/33c52777b4d032b317752bd9ed65b220 to your computer and use it in GitHub Desktop.
LinkedIn Query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
rohitsharmaj7
commented
Jul 10, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment