Javascript operators [duplicate] - javascript

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.

Related

Javascript syntax: variable declaration with "<<" or ">>"

I had a look at Jason Davies's Word Cloud source on Github
and within the index.js there are some variables that are declared like this:
cw = 1 << 11 >> 5,
ch = 1 << 11;
I noticed this pattern:
value before "<<" multiplies the value after "<<";
value after "<<" is a 2 to the power of the value specified;
value after ">>" (following "<<") divides that number before (which is also 2 two the power of the value);
I was curious:
in general what are the uses for this type of declaration and where does it come from
how does it add value to the code in the rest of the Jason Davies' layout?
See this link
Basically, << and >> do bit-wise shifts. If you do a << b, it will represent a as a number in base 2 (0s and 1s) and shift all the digits to the left by b positions. This is mathematically equivalent to
a * 2^b
The >> is the same principle, but it shifts to the right. It's almost analogous to a division by a factor of 2, but there's a special case when the intial number is odd: it floors the result.
⌊(a / 2^b)⌋
If you have 1 << 11 >> 5, the left and right shifts cancel each other, we end up in reality with
1 << 6 === 64 === 1 * 2^6

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

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

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.

Next odd number in javascript

To find the next odd number for an input the following code is being used:
a=5.4; // Input
b=Math.ceil(a); // Required to turn input to whole number
b=b+(((b % 2)-1)*-1); // Gives 7
The ceil rounding function is required.
Is this safe and is there a more compact way to do this?
EDIT: When the input is already an odd whole number then nothing happens. For example 5.0 will return 5
How about just
b += b % 2 ^ 1;
The remainder after dividing by 2 will always be 0 or 1, so the ^ operator (exclusive-OR) flips it to the opposite.
(Also, (b & 1) ^ 1 would work too. Oh, I guess b = b ^ 1 would work for positive integers, but it'd be problematic for big integers.)
At the question author's request:
The most compact way to achieve it is
b = Math.ceil(a) | 1;
First use ceil() to obtain the smallest integer not smaller than a, then obtain the smallest odd integer not smaller than ceil(a) by doing a bitwise or with 1 to ensure the last bit is set without changing anything else.
To obtain the smallest odd integer strictly larger than a, use
b = Math.floor(a+1) | 1;
Caveats:
Bit-operators operate on signed 32-bit integers in Javascript, so the value of a must be smaller than or equal to 2^31-1, resp. strictly smaller for the second. Also, a must be larger than -2^31-1.
If the representation of signed integers is not two's complement, but ones' complement or sign-and-magnitude (I don't know whether Javascript allows that, Java doesn't, but it's a possibility in C), the value of a must be larger than -1 -- the result of Math.ceil(a) resp. Math.floor(a+1) must be nonnegative.
Not really shorter, but this is more legible:
a=5.4;
b=Math.ceil(a);
b = b % 2 ? b : b + 1;
Try this:
a = 5.4
b = Math.ceil(a)
b = b%2 == 0 ? b+1 : b
y = Math.ceil((x - 1)/2)*2 + 1
Execute fn on http://www.intmath.com/functions-and-graphs/graphs-using-jsxgraph.php
Without Math.ceil() it can be done so:
b = a + a % 2 | 0 + 1;
NB. I consider next odd number of 5.0 as 7.

Can someone translate this simple function into Javascript?

I'm reading a tutorial on Perlin Noise, and I came across this function:
function IntNoise(32-bit integer: x)
x = (x<<13) ^ x;
return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);
end IntNoise function
While I do understand some parts of it, I really don't get what are (x<<13) and & 7fffffff supposed to mean (I see that it is a hex number, but what does it do?). Can someone help me translate this into JS? Also, normal integers are 32 bit in JS, on 32 bit computers, right?
It should work in JavaScript with minimal modifications:
function IntNoise(x) {
x = (x << 13) ^ x;
return (1 - ((x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824);
}
The << operator is a bitwise left-shift, so << 13 means shift the number 13 bits to the left.
The & operator is a bitwise AND. Doing & 0x7fffffff on a signed 32-bit integer masks out the sign bit, ensuring that the result is always a positive number (or zero).
The way that JavaScript deals with numbers is a bit quirky, to say the least. All numbers are usually represented as IEEE-754 doubles, but... once you start using bitwise operators on a number then JavaScript will treat the operands as signed 32-bit integers for the duration of that calculation.
Here's a good explanation of how JavaScript deals with bitwise operations:
Bitwise Operators
x<<13 means shift x 13 steps to left (bitwise).
Furthermore a<<b is equivalent to a*2^b.
& 7ffffff means bitwise AND of leftside with 7FFFFFFF.
If you take a look at the bit pattern of 7FFFFFFF you will notice that the bit 32 is 0 and the rest of the bits are 1. This means that you will mask out bit 0-30 and drop bit 31.

Categories

Resources