Bit operations

Back to Algorithms

This section contains algorithms for working with the bit-representation of integers. Many of the problems in this section seem to require non-trivial algorithms at first, but then suprisingly can be solved using only a few well-chosen integer operations. For native integers these algorithms are often constant time.

For example, consider the problem of zeroing the bits above the first leading 1-bit. At first it seems that we need to know the index of the first leading 1-bit, and therefore spend a logarithmic time searching for it using the exponential binary search. However, this problem can be solved by a simple combination of exclusive-or, increment, decrement, and right-shift. This is constant time for a native integer.

These algoritms are particularly useful when dealing with algorithms in the w-bit RAM model. Then they act as basic building tools of data-structures and algorithms. In particular, we use them in the skip-fast trie data structure.

Learn more

Files

An aggregate file for bit tricks

Bit extraction

Bit masks

Bit module

Complexity of an integer

Computation of floor(2^w / n)

IEEE floating point numbers

Index of the highest bit

Index of the lowest bit

Number of leading one bits

Number of leading zero bits

Number of one bits

Sets bits in an unsigned integer.

Sets the bits below the first 1-bit

Testing for IEEE floating-point numbers

Testing for bit masks

Testing for dividing infinity.

Testing for flipping leading bits

Testing for integer complexity

Testing for leading zero/one bits

Testing for lowest bit.

Testing for zeroing higher bits

Testing template

Zero bits above the first 1-bit

Zeros the bits below the first 0-bit