ADBlinnikov
7/16/2017 - 6:07 PM

Bitwise operators

Bitwise operators can be used to create complex boolean logic expressions.

/* Bitwise AND (a & b)
Returns a one in each bit position for which
the corresponding bits of both operands are ones. */
// Return true if integer is odd

integer & 1;

/* Bitwise OR (a | b)
Returns a zero in each bit position for which
the corresponding bits of both operands are zeros.*/

/* Bitwise NOT (~ a)
Inverts the bits of its operand.*/

// Convert integer to -(n + 1)
~2 === -3;
~-1 === 0;

// Convert float to integer woth double NOT
~~2.4 === 2;
~~3.9 === 3;

/* Bitwise XOR (a ^ b)
Returns a zero in each bit position for
which the corresponding bits are the same.*/

// Toggle switch

var itch = 1;
itch ^= 1; // 0
itch ^= 1; // 1

// True if two integers have opposite sign

(x ^ y) < 0;

/* Left shift (a >> b)
Shifts a in binary representation b bits to the left,
shifting in zeros from the right.*/

// Deccimal to integer
41.13 >> 0 === 41;
-14.4 >> 0 === -14;

// Integer  division

20.5 >> 1 === (20 / 2);
21 >> 1 === (21 / 2 - 0.5);

/* Zero-fill right shift (a >>> b)
Shifts a in binary representation b bits to the right,
discarding bits shifted off, and shifting in zeros from the left.*/

// Equivalent to division by 2, with truncation, as long as 
// integer value does not exceed max size in Javascript.
integer >>> 1;

/* Examples */

// Example function to get 2 middle characters 
// for even string and only 1 - for odd

const getMiddle = s => s.substr(s.length - 1 >>> 1, (~s.length & 1) + 1);