Bit manipulation

Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization.

It is a fast, primitive action directly supported by the central processing unit (CPU), and is used to manipulate values for comparisons and calculations.

On most processors, the majority of bitwise operations are single cycle - substantially faster than division and multiplication and branches.

Using bit and logical operators, there is a simple expression which will return true (1) or false (0): The second half uses the fact that powers of two have one and only one bit set in their binary representation: If the number is neither zero nor a power of two, it will have '1' in more than one place: If inline assembly language code is used, then an instruction (popcnt) that counts the number of 1's or 0's in the operand might be available; an operand with exactly one '1' bit is a power of 2.

Programming languages don't directly support most bit operations, so idioms must be used to code them.

[1] There's no simple programming language idiom, so it must be provided by a compiler intrinsic or system library routine.

More comprehensive applications of masking, when applied conditionally to operations, are termed predication.