Bit Manipulation in C++

0
95
Learn C++ free with free4dev
Learn C++ free with free4dev
This entry is part 6 of 6 in the series Learn C++

Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization. For most other tasks, modern programming languages allow the programmer to work directly with abstractions instead of bits that represent those abstractions. Source code that does bit manipulation makes use of the bitwise operations: AND, OR, XOR, NOT, and possibly other operations analogous to the boolean operators; there are also bit shifts and operations to count ones and zeros, find high and low one or zero, set, reset and test bits, extract and insert fields, mask and zero fields, gather and scatter bits to and from specified bit positions or fields. Integer arithmetic operators can also effect bit-operations in conjunction with the other operators.

Remove rightmost set bit

C-style bit-manipulation

Explanation

  • if n is zero, we have 0 & 0xFF..FF which is zero
  • else n can be written 0bxxxxxx10..00 and n - 1 is 0bxxxxxx011..11, so n & (n - 1) is 0bxxxxxx000..00.

Set all bits

C-style bit-manipulation

(See here for an explanation of why this works and is actually the best approach.)

Using std::bitset

Toggling a bit

C-style bit-manipulation

A bit can be toggled using the XOR operator (^).

Using std::bitset

Checking a bit

C-style bit-manipulation

The value of the bit can be obtained by shifting the number to the right x times and then performing bitwise AND (&) on it:

The right-shift operation may be implemented as either an arithmetic (signed) shift or a logical (unsigned) shift. If number in the expression number >> x has a signed type and a negative value, the resulting value is implementation-defined.

If we need the value of that bit directly in-place, we could instead left shift the mask:

Either can be used as a conditional, since all non-zero values are considered true.

Using std::bitset

Counting bits set

The population count of a bitstring is often needed in cryptography and other applications and the problem has been widely studied.

The naive way requires one iteration per bit:

A nice trick (based on Remove rightmost set bit ) is:

It goes through as many iterations as there are set bits, so it’s good when value is expected to have few nonzero bits.

The method was first proposed by Peter Wegner (in CACM 3 / 322 – 1960) and it’s well known since it appears in C Programming Language by Brian W. Kernighan and Dennis M. Ritchie.

This requires 12 arithmetic operations, one of which is a multication:

This kind of implementation has the best worst-case behavior (see Hamming weight for further details).

Many CPUs have a specific instruction (like x86’s popcnt) and the compiler could offer a specific (non standard) built in function. E.g. with g++ there is:

Check if an integer is a power of 2

The n & (n - 1) trick (see Remove rightmost set bit) is also useful to determine if an integer is a power of 2:

Note that without the first part of the check (n &&), 0 is incorrectly considered a power of 2.

Setting a bit

C-style bit manipulation

A bit can be set using the bitwise OR operator (|).

Using std::bitset

set(x) or set(x,true) – sets bit at position x to 1.

Clearing a bit

C-style bit-manipulation

A bit can be cleared using the bitwise AND operator (&).

Using std::bitset

reset(x) or set(x,false) – clears the bit at position x.

Changing the nth bit to x

C-style bit-manipulation

Using std::bitset

set(n,val) – sets bit n to the value val.

Bit Manipulation Application: Small to Capital Letter

One of several applications of bit manipulation is converting a letter from small to capital or vice versa by choosing a mask and a proper bit operation. For example, the a letter has this binary representation 01(1)00001 while its capital counterpart has 01(0)00001. They differ solely in the bit in parenthesis. In this case, converting the a letter from small to capital is basically setting the bit in parenthesis to one. To do so, we do the following:

The code for converting a letter to A letter is

The result is

Series NavigationPrevious: Bit Operators in C++

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.