Page 156 - JavaScript
P. 156
Bitwise XOR
The bitwise XOR (exclusive or) operation a ^ b places a 1 only if the two bits are different.
Exclusive or means either one or the other, but not both.
13 ^ 7 => 10
// 13: 0..01101
// 7: 0..00111
//-----------------
// 10: 0..01010 (0 + 8 + 0 + 2 + 0)
Real world example: swapping two integer values without additional memory allocation
var a = 11, b = 22;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log("a = " + a + "; b = " + b);// a is now 22 and b is now 11
Shift Operators
Bitwise shifting can be thought as "moving" the bits either left or right, and hence changing the
value of the data operated on.
Left Shift
The left shift operator (value) << (shift amount) will shift the bits to the left by (shift amount) bits;
the new bits coming in from the right will be 0's:
5 << 2 => 20
// 5: 0..000101
// 20: 0..010100 <= adds two 0's to the right
Right Shift (Sign-propagating)
The right shift operator (value) >> (shift amount) is also known as the "Sign-propagating right
shift" because it keeps the sign of the initial operand. The right shift operator shifts the value the
specified shift amount of bits to the right. Excess bits shifted off the right are discarded. The new
bits coming in from the left will be based on the sign of the initial operand. If the left-most bit was 1
then the new bits will all be 1 and vise-versa for 0's.
20 >> 2 => 5
// 20: 0..010100
// 5: 0..000101 <= added two 0's from the left and chopped off 00 from the right
-5 >> 3 => -1
// -5: 1..111011
// -2: 1..111111 <= added three 1's from the left and chopped off 011 from the right
https://riptutorial.com/ 113

