Bitwise Operators in C Programming Language
When I first learn C, I found it’s hard to understand the set of bitwise operations, it took me long time to search useful resources while still don’t make sense. However my life changed until I found a famous book wrote by K&RC, The C Programming Language. It is the work of Brian Kernighan and Dennis Ritchie (who created the C language), I Strongly Recomand to Read this book if you want to learn C.
1. Bitwise Operators
C provide six operators for bit manipulation, they are applied to integral operands, char, short, int and long:
Op. | Desc. |
---|---|
& | bitwise AND |
| | bitwise inclusive OR |
^ | bitwise exclusive OR |
<< | left shift |
>> | right shift |
~ | one’s complement (unary) |
2. How to Use ?
- Bitwise AND & often used to mask off some set of bits:
n = n & 0177; // set to zero all but lower 7 bits
- Bitwise inclusive OR | is used to turn bits on:
x = x | SET_ON; // sets to one in x the bits that are set to one in SET_ON
- Bitwise exclusive OR operator ^ sets a one in each bit position where its operands have different bits, and zero where they are the same.
As an illustration of some of the bit operators, consider the function getbits(x,p,n) that returns the (right adjusted) n-bit field of x that begins at position p:
// getbits: get n bits from the position p
unsigned getbits(unsigned x, int p, int n) {