What is the meaning of "<<" in javascript? [duplicate] - javascript

This question already has answers here:
What are bitwise shift (bit-shift) operators and how do they work?
(10 answers)
Closed 6 years ago.
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.

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.

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:

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

Related

Why does 100 >> 100 and 100 >>> 100 return 6 in Javascript? [duplicate]

This question already has answers here:
Javascript's Shift right with zero-fill operator (>>>) yielding unexpected result
(2 answers)
Closed 1 year ago.
From the documentation:
The right shift operator (>>) shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".
From what I understand, since 100 is 0b1100100, shifting it 100 times to the right should yield 0b0. However, when I run 100 >> 100 in Javascript (using chrome), it returns 6. Why is this the case? I am guessing it has something to do with JS's internal representation of numbers but would like to know more clearly.
Edit: The answer is still 6, even when using the unsigned >>> operator. Sign/unsigned does not seem to matter.
Unsigned operation documentation:
The unsigned right shift operator (>>>) (zero-fill right shift) shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative. Unlike the other bitwise operators, zero-fill right shift returns an unsigned 32-bit integer.
The value to the right is taken mod 32. (i.e. Only the last five bits are used.) If you calculate 100>>32, you get 100, which is the same thing you get when you compute 100>>0. After that, 100>>33 is 50, and the cycle repeats.

Javascript operators [duplicate]

This question already has answers here:
Unfamiliar characters used in JavaScript encryption script
(3 answers)
Closed 8 years ago.
I am using a "LightenDarkenColor" function in my script and never really paid much attention to it until now and I noticed some operations and I had no idea what they were doing. I had actually never seen them before.
Those operators are >> and &. I also noticed that the function doesn't work in Firefox.
The function:
function LightenDarkenColor(color, percent) {
var num = parseInt(color,16),
amt = Math.round(2.55 * percent),
R = (num >> 16) + amt,
B = (num >> 8 & 0x00FF) + amt,
G = (num & 0x0000FF) + amt;
return (0x1000000 + (R<255?R<1?0:R:255)*0x10000 + (B<255?B<1?0:B:255)*0x100 + (G<255?G<1?0:G:255)).toString(16).slice(1);
}
What exactly are the operators and how do they work?
Imagine num is 227733 (= some mild dark green) and take
B = (num >> 8 & 0x00FF)
num >> 8 will shift the number (move digits) to the right by 2 hex digits (4 bits per digit x 2=8) making it become:
227733 => 002277
then & 0x00FF will clear out all digits except the last two
002277 => 000077
and that is the component for green.
Hex 00FF is binary 0000000011111111 and & (binary AND) is the operation that will compare all bit pairs one by one and set all bits to zero unless both operand bits are 1s. So ANDing to zeroes will lead to zeroes, and ANDing to ones will give as result the same digits of the other operand: 1 & 1 => 1, 0 & 1=>0. Ones remain ones, zeroes remain zeroes. So AnyNumber & 0000000011111111 = the right part (lower 2 digits) of AnyNumber.
It is just the standard way of getting a number subpart. In this case the green component. Shift right to clear the lower bits, and &0000...1111 to clear the upper bits.
After it got all color components, it adds amt to all of them (amt positive=lighter) and at the end it crops the values
R<255?R<1?0:R:255 means: if less then 0 use 0, if more than 255 use 255.
And finally restores the color as a single number (instead of *0x100 could have used R<<8 that is the opposite of >>8, instead of +, it could have used |, binary OR, to merge the components).
Note that the function uses B as the second component, assuming it is blue but in reality in RGB the second is Green. Yet the result is correct anyway (it would work whatever color components you used and however you named them)
They're bitwise operators.
>> is a bitwise (Sign-propagating) right shift,
& is a bitwise "and".
I could go into detail on what these operators do, but the MDN has a good explanation and example for each operator. It would be counter-productive to copy those.

what does the symbol >> means in javascript

What does the >> symbol mean? On this page, there's a line that looks like this:
var i = 0, l = this.length >> 0, curr;
It's bitwise shifting.
Let's take the number 7, which in binary is 0b00000111
7 << 1 shifts it one bit to the left, giving you 0b00001110, which is 14
Similarly, you can shift to the right: 7 >> 1 will cut off the last bit, giving you 0b00000011 which is 3.
[Edit]
In JavaScript, numbers are stored as floats. However, when shifting you need integer values, so using bit shifting on JavaScript values will convert it from float to integer.
In JavaScript, shifting by 0 bits will round the number down* (integer rounding) (Better phrased: it will convert the value to integer)
> a = 7.5;
7.5
> a >> 0
7
*: Unless the number is negative.
Sidenote: since JavaScript's integers are 32-bit, avoid using bitwise shifts unless you're absolutely sure that you're not going to use large numbers.
[Edit 2]
this.length >> 0 will also make a copy of the number, instead of taking a reference to it. Although I have no idea why anyone would want that.
Just like in many other languages >> operator (among << and >>>) is a bitwise shift.

">>1" equals "/2"? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
>> in javascript
Here:
var num=10;
console.log(num/2);
num=4;
console.log(num/2);
It gives me 5 and 2.
And this one:
var num=10;
console.log(num>>1);
num=4;
console.log(num>>1);
It also gives me 5 and 2.
So x/2 is the same as x>>1? But why?
For the same reason that dropping the last digit off a normal (decimal) number is the same as dividing it by 10 (ignoring, of course, any non-integer remainder).
In computers, integers are internally represented in binary (base 2). So each digit represents a power of 2 instead of a power of 10 that we're used to with the decimal system.
>> 1 just means to shift all the bits right by one, which is another way of saying "drop the last digit". Since the digits are in binary, that's equivalent to dividing by the base, which is 2.
Similarly, if you need to divide by any power of 2, you can do so using the right shift operator: To divide by 4, shift by 2; to divide by 8, shift by 3; and so on.
Note that internally, it's often more efficient to do a shift operation instead of a division operation, but any compiler worth its salt will do this optimization for you (so that you don't have to write obfuscated code to get the performance benefit -- generally, you would only use the shift operator when your intention is to manipulate bits directly, and use the division operator when your intention is to do math).
x>>1 is a bit shift, which operates on the number's binary representation. The effect is that x>>n is the same as x/(2^n) (except that bit shift is usually faster than division, as it is lower level).
When you >> something, you basically shift all its bits to the right.
When that happens, you shift the 2-place value into the 1-place value, and the 4-place value into the 2-place value, and so on.
This effectively divides a number in half.
Take the number 14, for example:
1110.
When you shift the bits, you get 111, or 7.
Take a look at this:
http://en.wikipedia.org/wiki/Division_by_two#Binary
Everything you need to know about >> can be found here and here.

JavaScript | operator [duplicate]

This question already has answers here:
Using bitwise OR 0 to floor a number
(7 answers)
Closed 8 years ago.
Anyone able to explain what "|" and the value after does? I know the output for 0 creates sets of 13, the numbers, 3, 2, 1, 0. But what about | 1, or | 2.
var i = 52;
while(i--) {
alert(i/13 | 0);
}
It is the bitwise OR operator. There is both an explanation and an example over at MDC. Since doing bitwise OR with one operand being 0 produces the value of the other operand, in this case it does exactly nothing rounds the result of the division down.
If it were written | 1 what it would do is always print odd numbers (because it would set the 1-bit to on); specifically, it would cause even numbers to be incremented by 1 while leaving odd numbers untouched.
Update: As the commenters correctly state, the bitwise operator causes both operands to be treated as integers, therefore removing any fraction of the division result. I stand corrected.
This is a clever way of accomplishing the same effect as:
Math.floor(i/13);
JavaScript developers seem to be good at these kinds of things :)
In JavaScript, all numbers are floating point. There is no integer type. So even when you do:
var i = 1;
i is really the floating point number 1.0. So if you just did i/13, you'd end up with a fractional portion of it, and the output would be 3.846... for example.
When using the bitwise or operator in JavaScript, the runtime has to convert the operands to 32 bit integers before it can proceed. Doing this chops away the fractional part, leaving you with just an integer left behind. Bitwise or of zero is a no op (well, a no op in a language that has true integers) but has the side effect of flooring in JavaScript.
It's a bitwise operator. Specifically the OR Bitwise Operator.
What it basically does is use your var as an array of bits and each corresponding bit is with eachother. The result is 1 if any of them is 1. And 0 if both are 0.
Example:
24 = 11000
10 = 1010
The two aren't of equal length so we pad with 0's
24 = 11000
10 = 01010
26 = 11010
24 | 10 = 26
Best way to learn this is to readup on it.
That is the bitwise OR. In evaluating the expression, the LHS is truncated to an integer and returned, so | is effecively the same as Math.floor().

Categories

Resources