Bitwise Operators in C PDF
Bitwise Operators in C PDF
Alark Joshi
Motivation
High-level languages, for the most part, try to
make you as unaware of the hardware as
possible.
Not entirely true, because efficiency is still a
major consideration for some programming
languages.
C was created to make it easier to write
operating systems.
Motivation
Writing operating systems requires the
manipulation of data at addresses, and this
requires manipulating individual bits or groups of
bits.
Rather than write UNIX in assembly(tedious &
not portable due to specific ISA)
Goal - language that provided good control-flow,
some abstractions (structures, function calls), and
could be efficiently compiled and run quickly
Bitwise Operators
Bitwise operators only work on a limited
number of types: int and char
Two types of Bitwise operators
Unary bitwise operators
Binary bitwise operators
Bitwise Operators
Only one unary operator NOT
Binary bitwise operators
AND (&)
x&y
OR (|)
x|y
XOR (^)
x^y
Bitshift Operators
The << and >> operators have different meanings
in C and C++
In C, they are bitshift operators
In C++, they are stream insertion and extraction
operators
Bitshift Operators
Operator <<
x << n shifts the bits for x leftward by n bits
Bitshift Operators
Operator >>
x >> n shifts the bit rightward by n bits
Bit operations
Checking whether bit i is set
Ideas?
Masks
If you need to check whether a specific bit is set,
then you need to create an appropriate mask and
use bitwise operators
For e.g., x= 1111 0111, m = 0000 1000 => x&m
Creating a Mask
unsigned char mask = 1 << i ;
Causes ith bit to be set to 1. Since we are testing if
bit i is set
{
unsigned char mask = 1 << i ;
return mask & ch ;
Setting a bit
Create a mask
Followed by using a bitwise OR operator
unsigned char setBit( unsigned char ch, int i )
{
unsigned char mask = 1 << i ;
return mask | ch ; // using bitwise OR
}
In-class exercise
Write a function that clears bit i (i.e., makes
bit i's value 0).
unsigned char setBit( unsigned char ch, int i )
{
unsigned char mask = 1 << i ;
return mask ^ ch ; // using bitwise XOR
}
// And NOT works for any bit
Homework Exercises
Write a function that sets bit
from bhigh...blow to all 1's, while leaving the
remaining bits unchanged.
Write a function that clears bits
from bhigh...blow to all 0's, while leaving the
remaining bits unchanged.
Bit operators
Is Any Bit Set Within a Range?
bool isBitSetInRange(char ch, int low, int
high ) ;
Think about it
}
As long as at least one bit is 1, then the result is non-zero, and thus, the return
value is true.
Homework Exercise
Write a function to find out whether an
integer is a power of two.
References
The C Programming Language Kernighan
and Ritchie
Computer Organization & Design: The
Hardware/Software Interface, David Patterson
& John Hennessy, Morgan Kaufmann
http://www.cs.umd.edu/class/spring2003/cm
sc311/Notes/index.html