WR Home      Topic Home      Chapter:  1  2  3 
<Previous Next>

Chapter 03

Commonly used bit-manipulation functions

Page 12

Some Questions on Bit Manipulation
Question: Create a "fence" of ones

Need of such function: For example if there is a byte:
unsigned char byte = 0b11000011;

and it is required to SET multiple (continuous) bits.
Say, Bit number 2,3,4,5 are to be set.

Bit number 76543210 |||||||| VVVVVVVV Initially byte = 0b10000001 Modified byte = 0b10111101
One way of doing this is:
byte = byte |   (1 << 0x05) |  (1 << 0x04)  | (1 << 0x03) | (1 << 0x02)  ;
Another way of doing this is to use a "fence" of ones:

mask = 0b00111100 ; byte = byte | mask ;
Write a Method (WAM) which returns a "mask" in which bits from i to j are SET
Example if i=2 and j=5 the return value (nammed as mask) will be:

j i | | V V Bit number 76543210 |||||||| VVVVVVVV mask = 0b00111100 <---- Return Value
The function prototype is given below:

unsigned char getFence(unsigned char i, unsigned char j) { unsigned char mask; return mask; }



WR Home      Topic Home      Chapter:  1  2  3 
<Previous Next>