How to Use Bitwise Operations in Low-Level Programming
In addition to the familiar arithmetic operations +, -, * and /, programming languages also support bitwise operations. Through these low-level operations, a programmer can access individual bits in a binary pattern regardless of the data type. Bitwise operations implement logical arithmetic and bit shifts and can provide much better efficiency than high-level operations.
Instructions
-
-
1
Place the NOT operator in front of a binary value to perform a bitwise NOT. This so-called one's complement operation reverses each bit value. In the C programming language, use the ~ symbol to indicate a NOT operation. For instance, if X is 0101, then ~X is 1010.
-
2
Perform logical arithmetic on binary values of equal length. Computers perform logical operations on each pair of bits going from right to left. In C, the symbols &, | and ^ indicate bitwise AND, OR and XOR operations, respectively.
-
-
3
Shift a bit pattern to the left or right, discarding bits that you shift off either end, to implement optimized multiplication (left shift) or division (right shift) by powers of two. The C language uses the << and >> operators for left and right bit shifting.
-
4
Determine the value of a particular bit in a binary number (a read-flag operation) by performing an AND operation. Create a new binary number (T, for instance) of the same length as the number you wish to examine (K, for instance). Set all the bits in T to zero, with the exception of bit N, where bit N in K is the bit that you are testing. After performing T AND K, the result will be zero if bit N in K is zero, or it will be non-zero if bit N in K is one.
-
5
Set a particular bit in a binary value to one (a write-flag operation). You can perform this operation in a manner similar to that of Step 4. If you want to set bit N of K to one, then set bit N in T to one and all other bits in T to zero. Perform the operation T OR K. The resulting number is identical to T, with the exception that bit N of T is one (regardless of whether it was previously one or zero).
-
1
Tips & Warnings
Don't confuse the bitwise operations AND, OR and XOR with their Boolean counterparts. For instance, C uses & for a bitwise AND and && for a Boolean AND.