0

A user named ZPiDER answered a question about generating random colour strings in JS.

Random color generator in JavaScript

This is the code:

"#"+((1<<24)*Math.random()|0).toString(16)

I am trying to parse it to understand how it works but I really don't get it. Could someone please Explain what the << means?

I tried google but I suspect that the search engines interpret the characters as special somehow.

Community
  • 1
  • 1
xerotolerant
  • 1,955
  • 4
  • 21
  • 39
  • Google for "JavaScript operators", pretty much any of the top results contains the answer. – Mifeet May 11 '16 at 13:26
  • I don't think it is fair to call this a duplicate of that question because I had no idea that it was called that in the first place. I searched for " << in javascript" and variations and didn't really come out with a name. Also, I thought it had something to do with input or output as I see it used in C++. – xerotolerant May 11 '16 at 13:46
  • I think the point is that this question is not useful for others since this kind of operator has already been explained on SO several times. Plus people won't be able to google it anyway ;) – Mifeet May 11 '16 at 13:52
  • Btw, next time, you can also check out http://symbolhound.com/ – Mifeet May 11 '16 at 13:52
  • Ok, I understand. Thanks for the link – xerotolerant May 11 '16 at 14:05

3 Answers3

1

This is a bit shift: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

The number 1 (2^0) is being shifted left 24 bits to become 16777216 (2^24). From the documentation:

<< (Left shift)

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

For example, 9 << 2 yields 36:

Community
  • 1
  • 1
Andonaeus
  • 872
  • 1
  • 5
  • 21
1

It is the left shift operator just like in many other languages like C or Java.

1<<24 means, the 1 left shifted by 24 bits, so you get 0x1000000. Multiplied by a random value (that is from 0 inclusive to 1 exclusive) you get something between 0x000000 and 0xFFFFFF. This is exactly what you want to do for a random color.

But keep in mind, that the author of this code does not respect, that this random function does not generated uniformly distributed random values. So it is likely that you do not get a "real" random color, but something very close to it.

UniversE
  • 2,419
  • 17
  • 24
0

<< or >> is bit operation, bit shift. This takes two arguments, for example x << y. This is x: 1 1 0 0 0 1 1 1 . Lets shift it by 3 bytes right: 1 1 1 1 1 0 0 0