Bitwise Operations

By Deane Barker

This is a computer programming term. It refers to operations that are performed on sequences of bits, in aggregate.

A byte is made up of eight bits, which can be 0 or 1. So a byte might look like this:

00011011

A bitstring (or bitpattern) is any sequence of bits – not necessarily an entire byte. A bitwise operation is when two (usually, with one exception) bitstrings are calculated against each other, much like when two numbers are added together.

There are four bitwise operations. Three of the four compare two bitstrings and return a new one (a “binary” operation). The fourth returns a new bitstring from a single bitstring (a “unary” operation).

To compare them, they compare the corresponding bits of each position – so they compared the first bits of each string to get a result, then the second bits, then the third, etc. The result is always another bitstring of the same length.

AND

The resulting bit is 1 if both calculated bits are 1. So.

0010
1110
----
0010

The third bit of the result is 1, because both the third bits of the two original bitstrings are 1.

OR

The resulting bit is 1 if one of the calculated bits are 1.

0010
1110
----
1110

At least one of the first, second, and third positions are 1, so the result for the first three positions is 1. The fourth position is 0 in both cases, so the result is 0.

NOT

This is the sole unary operation, meaning it only requires one bitstring. It simply returns the opposite.

0010
----
1101

XOR

This will return 1 if the bits are different, and 0 if the bits are the same. (XOR means “exclusive or.”)

0010
1110
----
1100

The first and second bits are different, resulting in 1. The third and fourth bits are the same, resulting in 0.

Usage

Once I understood what bitwise operations did, I went looking for why someone would need one. I read a lot, and the consensus is that’s pretty rare in modern computer programming. Modern languages are abstracted quite a bit from processor operations, and there are usually higher-level constructs in languages now that preclude the need for bitwise operations.

Some use cases I found were:

Many answers referred to speed optimization, which has never been a huge issue for me in the particular work that I do.

Why I Looked It Up

I just always wondered. It was an aspect of programming I never understood, and now I know why – it’s just not something I’ll come into contact with much.

This is item #111 in a sequence of 953 items.

You can use your left/right arrow keys to navigate