< Previous | Contents | Next >
Bit Operations
One class of operators manipulates numbers in an unusual way. These operators work at the bit level. They are used for certain kinds of low level tasks, often involving setting or reading bit-flags.
Table 34-5: Bit Operators
Operator Description
Operator Description
~ Bitwise negation. Negate all the bits in a number.
<< Left bitwise shift. Shift all the bits in a number to the left.
>> Right bitwise shift. Shift all the bits in a number to the right.
& Bitwise AND. Perform an AND operation on all the bits in two numbers.
| Bitwise OR. Perform an OR operation on all the bits in two numbers.
^ Bitwise XOR. Perform an exclusive OR operation on all the bits in two numbers.
Note that there are also corresponding assignment operators (for example, <<=) for all but bitwise negation.
Here we will demonstrate producing a list of powers of 2, using the left bitwise shift op- erator:
[me@linuxbox ~]$ for ((i=0;i<8;++i)); do echo $((1<<i)); done
1
2
4
8
16
32
64
128
[me@linuxbox ~]$ for ((i=0;i<8;++i)); do echo $((1<<i)); done
1
2
4
8
16
32
64
128