Definition

bitwise operator

A bitwise operator is a character representing an action that works on data at the bit level rather than with bytes or larger units of data, as is more common.

In contrast, most regular operators work with either single or multiple bytes, which in most systems contain eight bits. Not all programming languages support the use of bitwise operators. CJava, JavaScript, Python and Visual Basic are among those that do. Because they allow greater precision and require fewer resources, bitwise operators can make some code faster and more efficient. Examples of uses of bitwise operations include encryption, compression, graphics, communications over ports/sockets, embedded systems programming and finite state machines.

A bitwise operator works with the binary representation of a number rather than that number's value. The operand is treated as a set of bits, instead of as a single number. Bitwise operators are similar in most languages that support them.

JavaScript Bitwise Operators:

Operator

Name

Type

Action

&

Bitwise AND

binary

If bits of both operands are ones, returns a one in each   bit position

|

Bitwise OR

binary

If bits of either operand are ones, returns a one in a bit   position

^

Bitwise XOR

binary

If a single operand is a one, returns a one in a bit   position

~

Bitwise NOT

unary

Flips the bits in the operand

<< 

Left shift

binary

Shifts first operand a number of bits to the left as   specified in the second operand, shifting in zeroes from the right

>> 

Right shift

binary

Shifts first operand a number of bits to the right as   specified in the second operand, and discards displaced bits

>>> 

Zero-fill right shift

binary

Shifts first operand a number of bits to the right as   specified in the second operand, discards displaced bits, and shifts in   zeroes from the left

 Note: Left shift, right shift and zero-fill right shift are sometimes referred to as bit shift operators.

The following example compares two versions of JavaScript code used to map several form checkboxes to a single number:

      var combo = form.elements[0].checked*(Math.pow(2,2))
      + form.elements[1].checked*(Math.pow(2,1))
      + form.elements[2].checked*(Math.pow(2,0));

Bitwise operators can be used to do the same thing, but more efficiently:

     var combo = form.elements[0].checked << 2
      | form.elements[1].checked << 1
      | form.elements[2].checked << 0

This was last updated in July 2016

Continue Reading About bitwise operator

Dig Deeper on Core Java APIs and programming techniques

App Architecture
Software Quality
Cloud Computing
Security
SearchAWS
Close