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

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

Related

Difference between (|) Bitwise OR vs (^) Bitwise XOR in JavaScript

I'm really getting confused on the use of the | OR vs ^ XOR in JavaScript, illustrated in the simple example below;
(function sayHi(n){
if(n < 1) //base case
return;
console.log("Hi!!" | "Hello!!") ;
sayHi(n - 1); //recurse
})(5);
(function sayHi(n){
if(n < 1) //base case
return;
console.log("Hi!!" ^ "Hello!!") ;
sayHi(n - 1); //recurse
})(5);
(function sayHi(n){
if(n < 1) //base case
return;
console.log(2 | 6) ;
sayHi(n - 1); //recurse
})(5);
(function sayHi(n){
if(n < 1) //base case
return;
console.log(2 ^ 6) ;
sayHi(n - 1); //recurse
})(5);
I'm confused about when, how, why, where I should appropriate use | vs ^.
Can someone please help me make sense the major difference between OR and XOR operations?
I was reading the documentation for JavaScript from MDN web Docs to better understand the concept of bitwise operations, but I am struggling to understand their significant difference.
I just want to make sure I continue to use these operations correctly henceforth.
Thanks a lot for the anticipated help!
OR and XOR are different operators:
OR:
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
XOR
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
If you have two bits and combine these with OR, the result will be 1, if one of these bits or both are 1. If you combine them with XOR (Exclusive OR) then it will be 1 if only one of these bits are 1 (not if both).
| is a bitwise or
So, if either bit is set in two operands, it will be set in the result
^ is an exclusive or, so if one bit is set in one of the operands, it will be set in the result, otherwise, it will not be set.
var x,y;
for (x = 0; x <= 1; x++) {
for (y = 0; y <= 1; y++) {
console.log('XOR '+ x + "^" + y + "=" + (x^y));
console.log('OR '+ x + "|" + y + "=" + (x|y));
}
}
Bitwise operators are typically used for checking whether a bit is set in a binary or not. You can vision it as a set of boolean values been compact it as a string 11100101, where each bit is used to represent the boolean flag true or false, 1 for set and 0 for unset respectively.
Binary reading is done abit different from our usual English. It is done from right to left, with the most left bit been the most significant bit because it holds the greatest value and the left hand side bit been the least.
Example:
Value: 64 = binary 10000000
Value: 1 = binary 00000001
Now back to your question.
Q: I'm confused about when, how, why, where I should appropriate use | vs ^.
A:
Bitmask and its operators are more commonly seen in low level programming where memory is a constraint (small computing device) or on performance critical application.
Sounds advantageous to use right? But they have their downside as well and it is code readability. Memory is cheap and processing power is much more greater than what it used to be, so people tend to forgo this bit of advantage when doing high level application programming.
Q: Can someone please help me make sense the major difference between OR and XOR operations?
OR and XOR operations are used for comparing two binaries. Let say binary A and binary B.
In layman term. The OR operations | can be read as if the bit in A OR B is set then return as set, which is 1.
Example:
10000000 // Value 64 in binary
00000001 // Value 1 in binary
10000001 // Gives you 65 when you perform | OR operation
= 65
XOR operation works a bit like OR but it has another special ability that is when two bits are the same it returns you 0 instead.
Example:
10000001 // Value 65 in binary
10000000 // Value 64 in binary
00000001 // Gives you 1 when you perform ^ XOR operation
= 1
From memory, you generally only use the AND & operator to check whether a bit is set or not. So you might be more interested in it and also the shift operations.
Your code doesn't make sense, bitwise operators (OR, XOR, AND) can only be used on numbers, not strings.
Each number is represent in memory by bits, each of which is 1 or 0 (true or false, on or off, etc). 1 and 0 are digits, just like 1, 2, 3, 4 are digits in our counting system. This counting system used by computers is called binary.
Bitwise operations basically perform the namesake operation (OR, XOR, or AND) on every single bit in the two operands.
Take 5 ^ 3 (5 XOR 3) for example:
5 is represented in binary as 00000101
3 is represented in binary as 00000011
For each operation, you have a left input, and a right input.
XOR stands for eXclusive OR, and returns 1 if the left OR the right input is 1, but not if they are both 1.
OR returns 1 if either of the inputs is 1, so if both are 1, then the output will also be 1.
A bitwise operation on a number performs this for every corresponding bit in each number, so 5 ^ 3 = 00000110, which is 6.
Note: Binary numbers are written from right to left. Each digit corresponds to a power of 2, like how digits correspond to powers of 10 when counting. The leftmost digit represents the highest power of 2 (in this case, 2 to the 7th, which is 128).
0 ^ 0 = 0 for the first 5 bits
1 ^ 0 = 1 for the 6th bit
0 ^ 1 = 1 for the 7th bit
1 ^ 1 = 0 for the 8th bit
Meanwhile, 5 | 3 = 00000111, which is 7.
0 | 0 = 0 for the first 5 bits
1 | 0 = 1 for the 6th bit
0 | 1 = 1 for the 7th bit
1 | 1 = 1 for the 8th bit
They are different math (logical) operators, more related to math than JavaScript.
OR / |, or called "Inclusive OR", is similar to the English phrase "A and/or B", there are 3 possibilities: not A but B, not B but A, both A and B.
XOR / ^, or called "Exclusive OR", is similar to the English phrase "either A or B", there are only 2 possibilities: not A but B, not B but A. You can see that "both A and B" is excluded, so called "exclusive".
Reference:
https://en.wikipedia.org/wiki/Logical_connective

Calculation order rules left shift "Lsh" in Javascript

I am trying to understand the mathematically correct order in calculations when using shifting.
I found Javascript seems to be doing calculations in priority order of:
^ * / + - << >>
A binary calculator for example the Calculator of Windows10 uses the priority order of:
<< >> ^ * / + -
But what is the mathematically correct order in this case?
for example:
Calculator
1 + 3 Lsh 3 - 1 (result: 24)
Javascript
1 + 3 << 3 - 1 (result: 16)
Try It:
http://www.w3schools.com/code/tryit.asp?filename=F0L1LGPQX9T2
there is no "mathematically correct order" for this
mathematics considers exponential, multiplication/division, and addition/subtraction, but bitwise operations come with programming languages, see https://en.wikipedia.org/wiki/Order_of_operations#Programming_languages
Use PEMDAS method: Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction.
So it means correct order is ^ * / + - << >>.
JS Operator precedence table

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.

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.

What do "num & 8", "num >> 8" and "num >> 8 & 64" mean in javascript?

I am having a hard time googling because of the symbols.
What do num & 8, num >> 8 and num >> 8 & 64 mean in javascript?
They are bitwise operators
to get the hundreds digit [num]->[/ 100]->[% 10]
To extract bits, use the [&] object to mask out the bit you're interested in, then optionally bit shift with [>>].
For instance, to get bit 3 (counting from right starting with zero) [num]->[& 8]->[>> 3].
If you just want to use the calculation to control a logic object (like if or a ggate), you can skip the bit shift.
These are really not Max-specific questions, they are fundamental DP techniques.
Shift left <<
The following expression means, shift 2 binary numbers to left:
alert( 1 << 2 );
So binary this is (I'll take 8 bit for example), shift the bits to left, 2 places
00000001 = 1
00000010 = 2
00000100 = 4
Shift right >>
The following expression means, shift 2 binary numbers to left:
alert( 255 >> 2 );
So binary this is (I'll take 8 bit for example), shift the bits to right, 2 places
11111111 = 255
01111111 = 127
00111111 = 63
AND operator &
That's the and operator
So you got the following rules:
11110011 = 243
01001111 = 79
01000011 = 67 = RESULT
Which means, only the 1 numbers will stay in the result if both of them have 1's on the same position.

Categories

Resources