C Bitwise Operators
C Bitwise Operators
I For unsigned int, when the first "1" falls off the left edge, the
operation has overflowed.
I It means that you have multiplied by 2k such that the result is
larger than the largest possible unsigned int.
I Shifting left on signed values also works, but overflow occurs
when the most significant bit changes values (from 0 to 1, or 1
to 0).
Right shift operator
I Create a mask
I 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
I Write a function that clears bit i (i.e., makes bit i’s value 0).
unsigned char clearBit(unsigned char ch, int i)
{
unsigned char mask = 1 << i ;
return ~mask & ch ; // using & for clearing
}
// How about using mask ^ ch ?
Bit operators
I Method 2: No loops
I Combination of Bitwise operation and subtraction
I Need a mask with 1’s between blow and bhigh
I How can you get k 1’s?
I One method:
unsigned int mask = 1 << k;
mask = mask - 1; // mask -=1;
I Think about it
Computing the Mask
I Get the low and high bits
unsigned char maskHigh = (1 << (high + 1)) - 1;
unsigned char maskLow = (1 << low) - 1;
unsigned char mask = maskHigh - maskLow;
I Function now looks like
bool isBitSetInRange(char ch, int low, int high)
{
unsigned char maskHigh = (1 << (high + 1)) - 1;
unsigned char maskLow = (1 << low) - 1;
unsigned char mask = maskHigh - maskLow;
return ch & mask;
}
I As long as at least one bit is 1, then the result is non-zero, and thus,
the return value is true.
Another example