How pipeline operator works in custom timer? [duplicate] - javascript

console.log(0.5 | 0); // 0
console.log(-1 | 0); // -1
console.log(1 | 0); // 1
Why does 0.5 | 0 return zero, but any integer (including negative) returns the input integer? What does the single pipe ("|") do?

This is a bitwise or.
Since bitwise operations only make sense on integers, 0.5 is truncated.
x | 0 is x, if x is an integer.

Bit comparison is so simple it's almost incomprehensible ;) Check out this "nybble"
8 4 2 1
-------
0 1 1 0 = 6 (4 + 2)
1 0 1 0 = 10 (8 + 2)
=======
1 1 1 0 = 14 (8 + 4 + 2)
Bitwise ORing 6 and 10 will give you 14:
alert(6 | 10); // should show 14
Terribly confusing!

A single pipe is a bit-wise OR.
Performs the OR operation on each pair
of bits. a OR b yields 1 if either a
or b is 1.
JavaScript truncates any non-integer numbers in bitwise operations, so its computed as 0|0, which is 0.

This example will help you.
var testPipe = function(input) {
console.log('input => ' + input);
console.log('single pipe | => ' + (input | 'fallback'));
console.log('double pipe || => ' + (input || 'fallback'));
console.log('-------------------------');
};
testPipe();
testPipe('something');
testPipe(50);
testPipe(0);
testPipe(-1);
testPipe(true);
testPipe(false);

This is a Bitwsie OR (|).
The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). Numbers with more than 32 bits get their most significant bits discarded.
So, in our case decimal number is converted to interger 0.5 to 0.
= 0.5 | 0
= 0 | 0
= 0

Related

What is the best way to determine if a given number is a power of two?

Is there a more effective way to return true if n is a power of two or false if not?
function isPowerOfTwo(n) {
return Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
}
You can actually use ECMAScript5 Math.log:
function powerOfTwo(x) {
return (Math.log(x)/Math.log(2)) % 1 === 0;
}
Remember, in math, to get a logarithm with an arbitrary base, you can just divide log10 of the operand (x in this case) by log10 of the base. And then to see if the number is a regular integer (and not a floating point), just check if the remainder is 0 by using the modulus % operator.
In ECMAScript6 you can do something like this:
function powerOfTwo(x) {
return Math.log2(x) % 1 === 0;
}
See the MDN docs for Math.log2.
Source: Bit twiddling Hacks,
function powerOf2(v) {
return v && !(v & (v - 1));
}
You just bitwise AND the previous number with the current number. If the result is falsy, then it is a power of 2.
The explanation is in this answer.
Note:
This will not be 100% true for programming, mathematical, [also read 'interviewing']. Some edge cases not handled by this are decimals (0.1, 0.2, 0.8…) or zero values (0, 0.0, …)
Using bitwise operators, this is by far the best way in terms of efficiency and cleanliness of your code:
function PowerofTwo(n){
return ((x != 0) && !(x & (x - 1)));
}
what it does is checks the bits that make up the number, i.e. 8 looks like this:
1 0 0 0
x-1 or 7 in this case looks like this
0 1 1 1
when the bitwise operator & is used it invokes an && on each bit of the number (thus 1 & 1 = 1, 1 & 0 = 0, 0 & 1 = 0, 0 & 0 = 1):
1 0 0 0
-0 1 1 1
=========
0 0 0 0
since the number turns into an exact 0 (or false when evaluted as a boolean) using the ! flag will return the correct answer
if you were to do this with a number like 7 it would look like this:
0 1 1 1
-0 1 1 0
=========
1 1 1 0
returning a number greater than zero causing the ! flag to take over and give the correct answer.
A number is a power of 2 if and only if log base 2 of that number is whole. The function below computes whether or not that is true:
function powerOfTwo(n){
// Compute log base 2 of n using a quotient of natural logs
var log_n = Math.log(n)/Math.log(2);
// Round off any decimal component
var log_n_floor = Math.floor(log_n);
// The function returns true if and only if log_n is a whole number
return log_n - log_n_floor == 0;
}
Making use of ES6's Math.clz32(n) to count leading zeros of a 32-bit integer from 1 to 2³² - 1:
function isPowerOf2(n) {
return Math.clz32(n) < Math.clz32(n - 1);
}
/**
* #param {number} n
* #return {boolean}
*/
const isPowerOfTwo = function(n) {
if(n == 0) return false;
while(n % 2 == 0){
n = n/2
}
return n === 1
};
function PowerOfTwo(n){
// Exercise for reader: confirm that n is an integer
return (n !== 0) && (n & (n - 1)) === 0;
}
console.log(PowerOfTwo(3))
console.log(PowerOfTwo(4))
This is for a specific online course that requires an answer in a specific way.
Without using libraries and other methods just loops and .push.
you need to create an inner loop using while
it should start with 1
keep multiplying it with 2 until i,j,k or whatever is greater than the current number(array) so it will have to do 2 4 6 8 10 12 14 16 18 until it is greater than the number
then it will go to the outer loop then repeat again until
const numbers = [5, 3, 9, 30];
const smallestPowerOfTwo = arr => {
let results = new Array;
// The 'outer' for loop -
for (let i = 0; i < arr.length; i++) {
number = arr[i];
// The 'inner' while loop
j = 1;
while (j < number) { //starting from 1 then multiplied by 2 then by 2 again untill it is more than the number
j = j * 2;
}
results.push(j);
}
return results
}
console.log(smallestPowerOfTwo(numbers))

What do the operators ">>" (double arrow) and "|" (single pipe) mean in JavaScript?

I saw this in some JS code:
index = [
ascii[0] >> 2,
((ascii[0] & 3) << 4) | ascii[1] >> 4,
((ascii[1] & 15) << 2) | ascii[2] >> 6,
ascii[2] & 63
];
I'd quite like to know what a lot of this means. Specifically ">>", a single pipe "|" and the "&" symbol on the last line?
Much appreciated!
x >> y means to shift the bits of x by y places to the right (<< to the left).
x | y means to compare the bits of x and y, putting a 1 in each bit if either x or y has a 1 in that position.
x & y is the same as |, except that the result is 1 if BOTH x and y have a 1.
Examples:
#left-shifting 1 by 4 bits yields 16
1 << 4 = b00001 << 4 = b10000 = 16
#right-shifting 72 by 3 bits yields 9
72 >> 3 = b1001000 >> 3 = b1001 = 9
#OR-ing
8 | 2 = b1000 | b0010 = b1010 = 10
#AND-ing
6 & 3 = b110 & b011 = b010 = 2
For more information, search Google for "bitwise operators".
>> is a right bitwise shift. It takes the bits and shifts them right n places1. For example, let's examine 35 >> 2:
35 = 100011 shift two places
001000 = 8
And indeed, 35 >> 2 == 8.
| is a bitwise OR. It takes each bit in each operand and ORs them together. You can envision it as a sort of binary addition, but you don't carry when both top and bottom are 1. For example, here's 5 | 3:
5 = 101
3 = 011
| -----
111 = 7
And indeed, 5 | 3 == 7.
Finally, & is a bitwise AND. It takes each bit in each operand, except instead of giving 1 if either one bit OR the other is one, it gives 1 if one bit AND the other are both one. For example, here's 5 & 3:
5 = 101
3 = 011
& -----
001 = 1
Try it out; 5 & 3 == 1.
Some other ones you might want to be aware of are <<, which is a left bitwise shift, and ^, which is an XOR (0 when both bits are the same, 1 if they're different).
1 Actually, it's n modulo 32. 1 >> 32 is 1. Not sure why.
The >> and << operators are a bitwise shift. For example,
11 = 00001011
11 << 3 = 01011000 = 88
It is worth noting that m << n = m * 2^n and m >> n = m / 2^n. This is sometimes used to do very efficient multiplication/division by powers of 2.
The & and | are bitwise and and or respectively.
11 = 00001011
28 = 00011100
11 & 28 = 00001000 = 8
11 = 00001011
28 = 00011100
11 | 28 = 00011111 = 31
While I'm at it, I should mention the ^ operator, which is not used for power, but for bitwise exclusive-or.
11 = 00001011
28 = 00011100
11 ^ 28 = 00010111 = 23
& (Bitwise AND)
| (Bitwise OR)
<< (Left shift)
>> (Sign-propagating right shift)
Examples (from https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators):
Bitwise and:
9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
Left shift (9 << 2 shifts bits of 9 in binary, 2 bits to the left):
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
Looks like bitwise operators to me:
http://web.eecs.umich.edu/~bartlett/jsops.html
Edit: that ascii array was a dead give away... LOL

Javascript Integer Division, or is Math.floor(x) equivalent to x | 0 for x >= 0?

Looking at the following examples, it looks like Math.floor(x) is equivalent to x | 0, for x >= 0. Is that really true? If yes, why? (or how x | 0 is calculated?)
x = -2.9; console.log(Math.floor(x) + ", " + (x | 0)); // -3, -2
x = -2.3; console.log(Math.floor(x) + ", " + (x | 0)); // -3, -2
x = -2; console.log(Math.floor(x) + ", " + (x | 0)); // -2, -2
x = -0.5; console.log(Math.floor(x) + ", " + (x | 0)); // -1, 0
x = 0; console.log(Math.floor(x) + ", " + (x | 0)); // 0, 0
x = 0.5; console.log(Math.floor(x) + ", " + (x | 0)); // 0, 0
x = 2; console.log(Math.floor(x) + ", " + (x | 0)); // 2, 2
x = 2.3; console.log(Math.floor(x) + ", " + (x | 0)); // 2, 2
x = 2.9; console.log(Math.floor(x) + ", " + (x | 0)); // 2, 2
x = 3.1; console.log(Math.floor(x) + ", " + (x | 0)); // 3, 3
This can be useful to perform integer division in Javascript: (5 / 3) | 0 rather than Math.floor(5 / 3).
Bitwise operators convert numbers to a 32-bit sequence. So the alternatives you’re suggesting will only work with positive signed 32-bit floats, i.e. numbers from 0 to +2,147,483,647 (2^31-1).
Math.floor(2147483646.4); // 2147483647
2147483646.4 | 0; // 2147483647
// but…
Math.floor(2147483648.4); // 2147483648
2147483648.4 | 0; // -2147483648
Another difference: if x is not a number, the result of x | 0 might be different than that of Math.floor(x).
Math.floor(NaN); // NaN
NaN | 0; // 0
Other than that, the result should be similar to that of Math.floor(), as long as a positive number is used.
Here are some more examples + performance tests: http://jsperf.com/rounding-numbers-down
As per ECMAScript spec, §11.10 Binary Bitwise Operators:
Semantics
The production A : A # B, where # is one of the bitwise operators in the productions
above, is evaluated as follows:
1. Let lref be the result of evaluating A.
2. Let lval be GetValue(lref).
3. Let rref be the result of evaluating B.
4. Let rval be GetValue(rref).
5. Let lnum be ToInt32(lval).
6. Let rnum be ToInt32(rval).
7. Return the result of applying the bitwise operator # to lnum and rnum. The result
is a signed 32 bit integer.
This is how x | y is calculated:
x and y are parsed to Int32 and then apply the | operator to them.
Bitwise operations in JS are 32bit, that is the float is first "cast" into an "int".
"2.6" | 0 = 2 suggests that parseInt is being called.
The vertical bar is the bitwise-or operator. Since the bits of 0 are all zero, x|0 is in theory a no-op. But in order to evaluate it the operands must be integers, so x must be converted from floating point into an integer first. The conversion is made by eliminating the fractional part, so yes, for some x >= 0 we have x|0 == Math.floor(x).
Note that the result depends on the size and signness of the internal integer type. For example you get:
2147483648|0 == -2147483648 // 0x80000000
Math.pow(2,32)|0 == 0 // the lowest 32 bits are all 0
(x | 0) removes the bits after the ".", so we can get the next true relation:
x | 0 = (x < 0 ? -1 : 1) * Math.floor(Math.abs(x)) ;
x >> 0 has the same effect as x | 0, so :
x >> 0 = x | 0 = (x < 0 ? -1 : 1) * Math.floor(Math.abs(x)) ;

what is the difference between >> and >>> operators in JavaScript

Running the following JavaScript code shows 63 in both cases:
alert( 0xff >> 2 );
alert( 0xff >>> 2 );
What is the differences between >> and >>>? Their results seem to be equal.
>> is a bitwise operator, which shift the bits to the right. Any bits at the right are lost.
8 = 1000
^-->1
= 0000 = 0
>>> does the similar thing as >>, but it's unsigned, which means that it ranges from 0 to 232-1 instead of +/- 231-1.
To see the result of my first statement in action, let's use the bitwise operator to floor a number:
1.234 >> 0 = 1 // Ok, fraction lost
1.234 >>>0 = 1 // Ok, fraction lost
-1.23 >> 0 = -1 // Ok, fraction lost
-1.23 >>>0 = 4294967295 // (negative numbers are not within the range)
Math.pow(2,31) >> 0 = -2147483648 // 2^31 is out of range
Math.pow(2,31) >>> 0 = 2147483648
So, when the upper boundary of a range is exceeded, the calculation will continue at its lower range, and vice versa (eg <<). The following illustrates shows what happens when you use n = (n + 1) >> 0, and >>> 0, for n starting at the lowest boundary.
// Signed Unsigned
>> >>>
-2147483647 0
-2147483646 1
... ...
2147483646 4294967294
2147483647 4294967295
-2147483647 0
-2147483646 1
It is the Unsigned Right Shift Operator.
A few links:
Shift with zero fill
Shift with sign

how to convert -1 to 1 with javascript?

how to convert -1 to 1 with javascript ?
var count = -1; //or any other number -2 -3 -4 -5 ...
or
var count = 1; //or any other number 2 3 4 5 ...
result should be
var count = 1; //or any other number 2 3 4 5 ...
count = Math.abs(count)
// will give you the positive value of any negative number
The abs function turns all numbers positive: i.e Math.abs( -1 ) = 1
Alternative approach (might be faster then Math.abs, untested):
count = -5;
alert((count ^ (count >> 31)) - (count >> 31));
Note that bitwise operations in javascript are always in 32-bit.
If the number of interest is input... In addition to Math.abs(input)....
var count = (input < 0 ? -input : input);
jsFiddle example
(edit: as Some pointed out -input is faster than -1 * input)
The above makes use of the Javascript conditional operator. This is the only ternary (taking three operands) Javascript operator.
The syntax is:
condition ? expr1 : expr2
If the condition is true, expr1 is evaluated, if it's fales expr2 is evaluated.

Categories

Resources