mozilla

# Revision 17819 of Bitwise operators

• Revision slug: JavaScript/Reference/Operators/Bitwise_Operators
• Revision title: Bitwise Operators
• Revision id: 17819
• Created:
• Creator: J-Mackerel
• Is current revision? No
• Comment 12 words added, 2 words removed
Tags:

## Revision Content

### Summary

Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal `numbers`. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

 Operators Implemented in: JavaScript 1.0 ECMA Version: ECMA-262

The following table summarizes JavaScript's bitwise operators:

Operator Usage Description
Bitwise AND `a & b` Returns a one in each bit position for which the corresponding bits of both operands are ones.
Bitwise OR `a | b` Returns a one in each bit position for which the corresponding bits of either or both operands are ones.
Bitwise XOR `a ^ b` Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.
Bitwise NOT `~ a` Inverts the bits of its operand.
Left shift `a << b` Shifts `a` in binary representation `b` (< 32) bits to the left, shifting in zeros from the right.
Sign-propagating right shift `a >> b` Shifts `a` in binary representation `b` (< 32) bits to the right, discarding bits shifted off.
Zero-fill right shift `a >>> b` Shifts `a` in binary representation `b` (< 32) bits to the right, discarding bits shifted off, and shifting in zeros from the left.

### Signed 32-bit integers

The operands of all bitwise operators are converted to signed 32-bit integers in big-endian order and in two's complement format. Big-endian order means that the most significant bit (the bit position with the greatest value) is the left-most bit if the 32 bits are arranged in a horizontal line. Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, a.k.a. one's complement of the number) plus one. For example, the following encodes the integer 314 (base 10):

```00000000000000000000000100111010
```

The following encodes `~314`, i.e. the one's complement of `314`:

```11111111111111111111111011000101
```

Finally, the following encodes `-314,` i.e. the two's complement of `314`:

```11111111111111111111111011000110
```

The two's complement guarantees that the left-most bit is 0 when the number is positive and 1 when the number is negative. Thus, it is called the sign bit.

The number `0` is the integer that is composed completely of 0 bits.

```     0 (base 10) = 00000000000000000000000000000000 (base 2)
```

The number `-1` is the integer that is composed completely of 1 bits.

```     -1 (base 10) = 11111111111111111111111111111111 (base 2)
```

The number `-2147483648` (hexadecimal representation: `-0x80000000`) is the integer that is composed completely of 0 bits except the first (left-most) one.

```     -2147483648 (base 10) = 10000000000000000000000000000000 (base 2)
```

The number `2147483647` (hexadecimal representation: `0x7fffffff`) is the integer that is composed completely of 1 bits except the first (left-most) one.

```     2147483647 (base 10) = 01111111111111111111111111111111 (base 2)
```

The numbers `-2147483648` and `2147483647` are the minimum and the maximum integers representable throught a 32bit signed number.

### Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

• The operands are converted to 32-bit integers and expressed by a series of bits (zeros and ones).
• Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
• The operator is applied to each pair of bits, and the result is constructed bitwise.

#### & (Bitwise AND)

Performs the AND operation on each pair of bits. `a` AND `b` yields 1 only if both `a` and `b` are 1. The truth table for the AND operation is:

 a b a AND b 0 0 0 0 1 0 1 0 0 1 1 1

Example:

```     9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
```

Bitwise ANDing any number x with 0 yields 0.

Bitwise ANDing any number x with -1 yields x.

#### | (Bitwise OR)

Performs the OR operation on each pair of bits. `a` OR `b` yields 1 if either `a` or `b` is 1. The truth table for the OR operation is:

 a b a OR b 0 0 0 0 1 1 1 0 1 1 1 1
```     9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
```

Bitwise ORing any number x with 0 yields x.

Bitwise ORing any number x with -1 yields -1.

#### ^ (Bitwise XOR)

Performs the XOR operation on each pair of bits. `a` XOR `b` yields 1 if `a` and `b` are different. The truth table for the XOR operation is:

 a b a XOR b 0 0 0 0 1 1 1 0 1 1 1 0

Example:

```     9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
```

Bitwise XORing any number x with 0 yields x.

Bitwise XORing any number x with -1 yields ~x.

#### ~ (Bitwise NOT)

Performs the NOT operator on each bit. NOT `a` yields the inverted value (a.k.a. one's complement) of `a`. The truth table for the NOT operation is:

 a NOT a 0 1 1 0

Example:

``` 9 (base 10) = 00000000000000000000000000001001 (base 2)
--------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
```

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

### Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand.  The right operand should be less than 32, but if not only the low five bits will be used.

#### << (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:

```     9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
```

Bitwise shifting any number x to the left by y bits yields x * 2^y.

#### >> (Sign-propagating right shift)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".

For example, `9 >> 2` yields 2:

```     9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
```

Likewise, `-9 >> 2` yields -3, because the sign is preserved:

```     -9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
```

#### >>> (Zero-fill right shift)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always positive.

For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, `9 >>> 2` yields 2, the same as `9 >> 2`:

```      9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
```

However, this is not the case for negative numbers. For example, `-9 >>> 2` yields 1073741821, which is different than `-9 >> 2` (which yields -3):

```      -9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
```

### Examples

The bitwise logical operators are often used to create, manipulate, and read sequences of flags, which are like binary variables. Variables could be used instead of these sequences, but binary flags take much less memory (by a factor of 32).

Suppose there are 4 flags:

• flag A: we have an ant problem
• flag B: we own a bat
• flag C: we own a cat
• flag D: we own a duck

These flags are represented by a sequence of bits: DCBA. When a flag is set, it has a value of 1. When a flag is cleared, it has a value of 0. Suppose a variable `flags` has the binary value 0101:

```var flags = 0x5;   // binary 0101
```

This value indicates:

• flag A is true (we have an ant problem);
• flag B is false (we don't own a bat);
• flag C is true (we own a cat);
• flag D is false (we don't own a duck);

Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the preceding zeroes can be neglected since they contain no meaningful information.

A bitmask is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask for each flag is defined:

```var FLAG_A = 0x1; // 0001
var FLAG_B = 0x2; // 0010
var FLAG_C = 0x4; // 0100
var FLAG_D = 0x8; // 1000
```

New bitmasks can be created by using the bitwise logical operators on these primitive bitmasks. For example, the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:

```var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 => 1011
```

Individual flag values can be extracted by ANDing them with a bitmask, where each bit with the value of one will "extract" the corresponding flag. The bitmask masks out the non-relevant flags by ANDing with zeros (hence the term "bitmask"). For example, the bitmask 0100 can be used to see if flag C is set:

```// if we own a cat
if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
// do stuff
}
```

A bitmask with multiple set flags acts like an "either/or". For example, the following two are equivalent:

```// if we own a bat or we own a cat
if ((flags & FLAG_B) || (flags & FLAG_C)) { // (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true
// do stuff
}
```
```// if we own a bat or cat
var mask = FLAG_B | FLAG_C; // 0010 | 0100 => 0110
if (flags & mask) { // 0101 & 0110 => 0100 => true
// do stuff
}
```

Flags can be set by ORing them with a bitmask, where each bit with the value one will set the corresponding flag, if that flag isn't already set. For example, the bitmask 1010 can be used to set flags C and D:

```// yes, we own a cat and a duck
var mask = FLAG_C | FLAG_D; // 0100 | 1000 => 1100
flags |= mask;   // 0101 | 1100 => 1101
```

Flags can be cleared by ANDing them with a bitmask, where each bit with the value zero will clear the corresponding flag, if it isn't already cleared. This bitmask can be created by NOTing primitive bitmasks. For example, the bitmask 1010 can be used to clear flags A and C:

```// no, we don't neither have an ant problem nor own a cat
var mask = ~(FLAG_A | FLAG_C); // ~0101 => 1010
flags &= mask;   // 1101 & 1010 => 1000
```

The mask could also have been created with `~FLAG_A & ~FLAG_C` (De Morgan's law):

```// no, we don't have an ant problem, and we don't own a cat
var mask = ~FLAG_A & ~FLAG_C;
flags &= mask;   // 1101 & 1010 => 1000
```

Flags can be toggled by XORing them with a bitmask, where each bit with the value one will toggle the corresponding flag. For example, the bitmask 0110 can be used to toggle flags B and C:

```// if we didn't have a bat, we have one now, and if we did have one, bye-bye bat
// same thing for cats
var mask = FLAG_B | FLAG_C;
flags = flags ^ mask;   // 1100 ^ 0110 => 1010
```

Finally, the flags can all be flipped with the NOT operator:

```// entering parallel universe...
flags = ~flags;    // ~1010 => 0101
```

#### Conversion snippets

Convert a binary `string` to a decimal `number`:

```var sBinString = "1011";
var nMyNumber = parseInt(sBinString, 2);
alert(nMyNumber); // prints 11, i.e. 1011
```

Convert a decimal `number` to a binary `string`:

```var nMyNumber = 11;
var sBinString = nMyNumber.toString(2);
alert(sBinString); // prints 1011, i.e. 11
```

#### Automatize the creation of a mask

If you have to create many masks from some `boolean` values, you can automatize the process:

```function createMask () {
var nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 : arguments.length;
for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);
}
// etc.

```

#### Reverse algorithm: an array of booleans from a mask

If you want to create an `array` of `booleans` from a mask you can use this code:

```function arrayFromMask (nMask) {
// nMask must be between -2147483648 and 2147483647
if (nMask > 0x7fffffff || nMask < -0x80000000) { throw new TypeError("arrayFromMask - out of range"); }
for (nShifted; nShifted; aFromMask.push(Boolean(nShifted & 1)), nShifted >>= 1);
}

alert("[" + array1.join(", ") + "]");
// prints "[true, true, false, true]", i.e.: 11, i.e.: 1011
```

You can test both algorithms at the same time…

```var nTest = 19; // our custom mask

```

For didactic purpose only (since there is the `Number.toString(2)` method), we show how it is possible to modify the `arrayFromMask` algorithm in order to create a `string` containing the binary representation of a `number`, rather than an `array` of `booleans`:

```function createBinaryString (nMask) {
// nMask must be between -2147483648 and 2147483647
if (nMask > 0x7fffffff || nMask < -0x80000000) { throw new TypeError("createBinaryString - out of range"); }
for (var nFlag = 0, nShifted = nMask & 0x7fffffff; nFlag < 31; nFlag++, nShifted <<= 1) {
sMask += String((nShifted & 0x7fffffff) >> 30);
}
}

var string1 = createBinaryString(11);
var string2 = createBinaryString(4);
var string3 = createBinaryString(1);

// prints 00000000000000000000000000001011, i.e. 11
```

{{ languages( { "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Op\u00e9rateurs/Op\u00e9rateurs_binaires", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Operatory/Operatory_bitowe" } ) }}

## Revision Source

```<h3>Summary</h3>
<p>Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal <code><a href="/en/JavaScript/Reference/Global_Objects/Number" title="/en/JavaScript/Reference/Global_Objects/Number">numbers</a></code>. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.</p>
<table class="fullwidth-table"> <tbody> <tr> <td class="header" colspan="2">Operators</td> </tr> <tr> <td>Implemented in:</td> <td>JavaScript 1.0</td> </tr> <tr> <td>ECMA Version:</td> <td>ECMA-262</td> </tr> </tbody>
</table>
<p>The following table summarizes JavaScript's bitwise operators:</p>
<table class="fullwidth-table"> <tbody> <tr> <th>Operator</th> <th>Usage</th> <th>Description</th> </tr> <tr> <td>Bitwise AND</td> <td style="white-space: nowrap"><code>a &amp; b</code></td> <td>Returns a one in each bit position for which the corresponding bits of both operands are ones.</td> </tr> <tr> <td>Bitwise OR</td> <td style="white-space: nowrap"><code>a | b</code></td> <td>Returns a one in each bit position for which the corresponding bits of either or both operands are ones.</td> </tr> <tr> <td>Bitwise XOR</td> <td style="white-space: nowrap"><code>a ^ b</code></td> <td>Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.</td> </tr> <tr> <td>Bitwise NOT</td> <td style="white-space: nowrap"><code>~ a</code></td> <td>Inverts the bits of its operand.</td> </tr> <tr> <td>Left shift</td> <td style="white-space: nowrap"><code>a &lt;&lt; b</code></td> <td>Shifts <code>a</code> in binary representation <code>b</code> (&lt; 32) bits to the left, shifting in zeros from the right.</td> </tr> <tr> <td>Sign-propagating right shift</td> <td style="white-space: nowrap"><code>a &gt;&gt; b</code></td> <td>Shifts <code>a</code> in binary representation <code>b</code> (&lt; 32) bits to the right, discarding bits shifted off.</td> </tr> <tr> <td>Zero-fill right shift</td> <td style="white-space: nowrap"><code>a &gt;&gt;&gt; b</code></td> <td>Shifts <code>a</code> in binary representation <code>b</code> (&lt; 32) bits to the right, discarding bits shifted off, and shifting in zeros from the left.</td> </tr> </tbody>
</table>
<h3>Signed 32-bit integers</h3>
<p>The operands of all bitwise operators are converted to signed 32-bit integers in big-endian order and in two's complement format. Big-endian order means that the most significant bit (the bit position with the greatest value) is the left-most bit if the 32 bits are arranged in a horizontal line. Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, a.k.a. one's complement of the number) plus one. For example, the following encodes the integer 314 (base 10):</p>
<pre>00000000000000000000000100111010
</pre>
<p>The following encodes <code>~314</code>, i.e. the one's complement of <code>314</code>:</p>
<pre>11111111111111111111111011000101
</pre>
<p>Finally, the following encodes <code>-314,</code> i.e. the two's complement of <code>314</code>:</p>
<pre>11111111111111111111111011000110
</pre>
<p>The two's complement guarantees that the left-most bit is 0 when the number is positive and 1 when the number is negative. Thus, it is called the <em>sign bit</em>.</p>
<p>The number <code>0</code> is the integer that is composed completely of 0 bits.</p>
<pre>     0 (base 10) = 00000000000000000000000000000000 (base 2)
</pre>
<p>The number <code>-1</code> is the integer that is composed completely of 1 bits.</p>
<pre>     -1 (base 10) = 11111111111111111111111111111111 (base 2)
</pre>
<p>The number <code>-2147483648</code> (hexadecimal representation: <code>-0x80000000</code>) is the integer that is composed completely of 0 bits except the first (left-most) one.</p>
<pre>     -2147483648 (base 10) = 10000000000000000000000000000000 (base 2)
</pre>
<p>The number <code>2147483647</code> (hexadecimal representation: <code>0x7fffffff</code>) is the integer that is composed completely of 1 bits except the first (left-most) one.</p>
<pre>     2147483647 (base 10) = 01111111111111111111111111111111 (base 2)
</pre>
<p>The numbers <code>-2147483648</code> and <code>2147483647</code> are the minimum and the maximum integers representable throught a 32bit signed number.</p>
<h3>Bitwise logical operators</h3>
<p>Conceptually, the bitwise logical operators work as follows:</p>
<ul> <li>The operands are converted to 32-bit integers and expressed by a series of bits (zeros and ones).</li> <li>Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.</li> <li>The operator is applied to each pair of bits, and the result is constructed bitwise.</li>
</ul>
<h4>&amp; (Bitwise AND)</h4>
<p>Performs the AND operation on each pair of bits. <code>a</code> AND <code>b</code> yields 1 only if both <code>a</code> and <code>b</code> are 1. The truth table for the AND operation is:</p>
<table class="standard-table"> <tbody> <tr> <td class="header">a</td> <td class="header">b</td> <td class="header">a AND b</td> </tr> <tr> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <td>1</td> <td>1</td> <td>1</td> </tr> </tbody>
</table>
<p>Example:</p>
<pre>     9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 &amp; 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
</pre>
<p>Bitwise ANDing any number x with 0 yields 0.</p>
<p>Bitwise ANDing any number x with -1 yields x.</p>
<h4>| (Bitwise OR)</h4>
<p>Performs the OR operation on each pair of bits. <code>a</code> OR <code>b</code> yields 1 if either <code>a</code> or <code>b</code> is 1. The truth table for the OR operation is:</p>
<table class="standard-table"> <tbody> <tr> <td class="header">a</td> <td class="header">b</td> <td class="header">a OR b</td> </tr> <tr> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>0</td> <td>1</td> <td>1</td> </tr> <tr> <td>1</td> <td>0</td> <td>1</td> </tr> <tr> <td>1</td> <td>1</td> <td>1</td> </tr> </tbody>
</table>
<pre>     9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
</pre>
<p>Bitwise ORing any number x with 0 yields x.</p>
<p>Bitwise ORing any number x with -1 yields -1.</p>
<h4>^ (Bitwise XOR)</h4>
<p>Performs the XOR operation on each pair of bits. <code>a</code> XOR <code>b</code> yields 1 if <code>a</code> and <code>b</code> are different. The truth table for the XOR operation is:</p>
<table class="standard-table"> <tbody> <tr> <td class="header">a</td> <td class="header">b</td> <td class="header">a XOR b</td> </tr> <tr> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>0</td> <td>1</td> <td>1</td> </tr> <tr> <td>1</td> <td>0</td> <td>1</td> </tr> <tr> <td>1</td> <td>1</td> <td>0</td> </tr> </tbody>
</table>
<p>Example:</p>
<pre>     9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
</pre>
<p>Bitwise XORing any number x with 0 yields x.</p>
<p>Bitwise XORing any number x with -1 yields ~x.</p>
<h4>~ (Bitwise NOT)</h4>
<p>Performs the NOT operator on each bit. NOT <code>a</code> yields the inverted value (a.k.a. one's complement) of <code>a</code>. The truth table for the NOT operation is:</p>
<table class="standard-table"> <tbody> <tr> <td class="header">a</td> <td class="header">NOT a</td> </tr> <tr> <td>0</td> <td>1</td> </tr> <tr> <td>1</td> <td>0</td> </tr> </tbody>
</table>
<p>Example:</p>
<pre> 9 (base 10) = 00000000000000000000000000001001 (base 2)
--------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
</pre>
<p>Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.</p>
<h3>Bitwise shift operators</h3>
<p>The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.</p>
<p>Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand.  The right operand should be less than 32, but if not only the low five bits will be used.</p>
<h4>&lt;&lt; (Left shift)</h4>
<p>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.</p>
<p>For example, <code>9 &lt;&lt; 2</code> yields 36:</p>
<pre>     9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 &lt;&lt; 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
</pre>
<p>Bitwise shifting any number <strong>x</strong> to the left by <strong>y</strong> bits yields <strong>x * 2^y</strong>.</p>
<h4>&gt;&gt; (Sign-propagating right shift)</h4>
<p>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".</p>
<p>For example, <code>9 &gt;&gt; 2</code> yields 2:</p>
<pre>     9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 &gt;&gt; 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
</pre>
<p>Likewise, <code>-9 &gt;&gt; 2</code> yields -3, because the sign is preserved:</p>
<pre>     -9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 &gt;&gt; 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
</pre>
<h4>&gt;&gt;&gt; (Zero-fill right shift)</h4>
<p>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always positive.</p>
<p>For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, <code>9 &gt;&gt;&gt; 2</code> yields 2, the same as <code>9 &gt;&gt; 2</code>:</p>
<pre>      9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 &gt;&gt;&gt; 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
</pre>
<p>However, this is not the case for negative numbers. For example, <code>-9 &gt;&gt;&gt; 2</code> yields 1073741821, which is different than <code>-9 &gt;&gt; 2</code> (which yields -3):</p>
<pre>      -9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 &gt;&gt;&gt; 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
</pre>
<h3>Examples</h3>
<p>The bitwise logical operators are often used to create, manipulate, and read sequences of <em>flags</em>, which are like binary variables. Variables could be used instead of these sequences, but binary flags take much less memory (by a factor of 32).</p>
<p>Suppose there are 4 flags:</p>
<ul> <li>flag A: we have an ant problem</li> <li>flag B: we own a bat</li> <li>flag C: we own a cat</li> <li>flag D: we own a duck</li>
</ul>
<p>These flags are represented by a sequence of bits: DCBA. When a flag is <em>set</em>, it has a value of 1. When a flag is <em>cleared</em>, it has a value of 0. Suppose a variable <code>flags</code> has the binary value 0101:</p>
<pre class="brush: js">var flags = 0x5;   // binary 0101
</pre>
<p>This value indicates:</p>
<ul> <li>flag A is true (we have an ant problem);</li> <li>flag B is false (we don't own a bat);</li> <li>flag C is true (we own a cat);</li> <li>flag D is false (we don't own a duck);</li>
</ul>
<p>Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the preceding zeroes can be neglected since they contain no meaningful information.</p>
<p>A <em>bitmask</em> is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask for each flag is defined:</p>
<pre class="brush: js">var FLAG_A = 0x1; // 0001
var FLAG_B = 0x2; // 0010
var FLAG_C = 0x4; // 0100
var FLAG_D = 0x8; // 1000
</pre>
<p>New bitmasks can be created by using the bitwise logical operators on these primitive bitmasks. For example, the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:</p>
<pre class="brush: js">var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 =&gt; 1011
</pre>
<p>Individual flag values can be extracted by ANDing them with a bitmask, where each bit with the value of one will "extract" the corresponding flag. The bitmask <em>masks</em> out the non-relevant flags by ANDing with zeros (hence the term "bitmask"). For example, the bitmask 0100 can be used to see if flag C is set:</p>
<pre class="brush: js">// if we own a cat
if (flags &amp; FLAG_C) { // 0101 &amp; 0100 =&gt; 0100 =&gt; true
// do stuff
}
</pre>
<p>A bitmask with multiple set flags acts like an "either/or". For example, the following two are equivalent:</p>
<pre class="brush: js">// if we own a bat or we own a cat
if ((flags &amp; FLAG_B) || (flags &amp; FLAG_C)) { // (0101 &amp; 0010) || (0101 &amp; 0100) =&gt; 0000 || 0100 =&gt; true
// do stuff
}
</pre>
<pre class="brush: js">// if we own a bat or cat
var mask = FLAG_B | FLAG_C; // 0010 | 0100 =&gt; 0110
if (flags &amp; mask) { // 0101 &amp; 0110 =&gt; 0100 =&gt; true
// do stuff
}
</pre>
<p>Flags can be set by ORing them with a bitmask, where each bit with the value one will set the corresponding flag, if that flag isn't already set. For example, the bitmask 1010 can be used to set flags C and D:</p>
<pre class="brush: js">// yes, we own a cat and a duck
var mask = FLAG_C | FLAG_D; // 0100 | 1000 =&gt; 1100
flags |= mask;   // 0101 | 1100 =&gt; 1101
</pre>
<p>Flags can be cleared by ANDing them with a bitmask, where each bit with the value zero will clear the corresponding flag, if it isn't already cleared. This bitmask can be created by NOTing primitive bitmasks. For example, the bitmask 1010 can be used to clear flags A and C:</p>
<pre class="brush: js">// no, we don't neither have an ant problem nor own a cat
var mask = ~(FLAG_A | FLAG_C); // ~0101 =&gt; 1010
flags &amp;= mask;   // 1101 &amp; 1010 =&gt; 1000
</pre>
<p>The mask could also have been created with <code>~FLAG_A &amp; ~FLAG_C</code> (De Morgan's law):</p>
<pre class="brush: js">// no, we don't have an ant problem, and we don't own a cat
var mask = ~FLAG_A &amp; ~FLAG_C;
flags &amp;= mask;   // 1101 &amp; 1010 =&gt; 1000
</pre>
<p>Flags can be toggled by XORing them with a bitmask, where each bit with the value one will toggle the corresponding flag. For example, the bitmask 0110 can be used to toggle flags B and C:</p>
<pre class="brush: js">// if we didn't have a bat, we have one now, and if we did have one, bye-bye bat
// same thing for cats
var mask = FLAG_B | FLAG_C;
flags = flags ^ mask;   // 1100 ^ 0110 =&gt; 1010
</pre>
<p>Finally, the flags can all be flipped with the NOT operator:</p>
<pre class="brush: js">// entering parallel universe...
flags = ~flags;    // ~1010 =&gt; 0101
</pre>
<h4>Conversion snippets</h4>
<p>Convert a binary <code><a href="/en/JavaScript/Reference/Global_Objects/String" title="/en/JavaScript/Reference/Global_Objects/String">string</a></code> to a decimal <code><a href="/en/JavaScript/Reference/Global_Objects/Number" title="/en/JavaScript/Reference/Global_Objects/Number">number</a></code>:</p>
<pre class="brush: js">var sBinString = "1011";
var nMyNumber = parseInt(sBinString, 2);
alert(nMyNumber); // prints 11, i.e. 1011
</pre>
<p>Convert a decimal <code><a href="/en/JavaScript/Reference/Global_Objects/Number" title="/en/JavaScript/Reference/Global_Objects/Number">number</a></code> to a binary <code><a href="/en/JavaScript/Reference/Global_Objects/String" title="/en/JavaScript/Reference/Global_Objects/String">string</a></code>:</p>
<pre class="brush: js">var nMyNumber = 11;
var sBinString = nMyNumber.toString(2);
alert(sBinString); // prints 1011, i.e. 11
</pre>
<h4>Automatize the creation of a mask</h4>
<p>If you have to create many masks from some <code><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="/en/JavaScript/Reference/Global_Objects/Boolean">boolean</a></code> values, you can automatize the process:</p>
<pre class="brush: js">function createMask () {
var nMask = 0, nFlag = 0, nLen = arguments.length &gt; 32 ? 32 : arguments.length;
for (nFlag; nFlag &lt; nLen; nMask |= arguments[nFlag] &lt;&lt; nFlag++);
}
// etc.

</pre>
<h4>Reverse algorithm: an array of booleans from a mask</h4>
<p>If you want to create an <code><a href="/en/JavaScript/Reference/Global_Objects/Array" title="/en/JavaScript/Reference/Global_Objects/Array">array</a></code> of <code><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="/en/JavaScript/Reference/Global_Objects/Boolean">booleans</a></code> from a mask you can use this code:</p>
// nMask must be between -2147483648 and 2147483647
if (nMask &gt; 0x7fffffff || nMask &lt; -0x80000000) { throw new TypeError("arrayFromMask - out of range"); }
for (nShifted; nShifted; aFromMask.push(Boolean(nShifted &amp; 1)), nShifted &gt;&gt;= 1);
}

alert("[" + array1.join(", ") + "]");
// prints "[true, true, false, true]", i.e.: 11, i.e.: 1011
</pre>
<p>You can test both algorithms at the same time…</p>
<pre class="brush: js">var nTest = 19; // our custom mask

</pre>
<p>For didactic purpose only (since there is the <code><a href="/en/JavaScript/Reference/Global_Objects/Number/toString" title="/en/JavaScript/Reference/Global_Objects/Number/toString">Number.toString(2)</a></code> method), we show how it is possible to modify the <code>arrayFromMask</code> algorithm in order to create a <code><a href="/en/JavaScript/Reference/Global_Objects/String" title="/en/JavaScript/Reference/Global_Objects/String">string</a></code> containing the binary representation of a <code><a href="/en/JavaScript/Reference/Global_Objects/Number" title="/en/JavaScript/Reference/Global_Objects/Number">number</a></code>, rather than an <code><a href="/en/JavaScript/Reference/Global_Objects/Array" title="/en/JavaScript/Reference/Global_Objects/Array">array</a></code> of <code><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="/en/JavaScript/Reference/Global_Objects/Boolean">booleans</a></code>:</p>
<pre class="brush: js">function createBinaryString (nMask) {
// nMask must be between -2147483648 and 2147483647
if (nMask &gt; 0x7fffffff || nMask &lt; -0x80000000) { throw new TypeError("createBinaryString - out of range"); }
for (var nFlag = 0, nShifted = nMask &amp; 0x7fffffff; nFlag &lt; 31; nFlag++, nShifted &lt;&lt;= 1) {
sMask += String((nShifted &amp; 0x7fffffff) &gt;&gt; 30);
}