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 onesNeed 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.
One way of doing this is:
Bit number 76543210 |||||||| VVVVVVVV Initially byte = 0b10000001 Modified byte = 0b10111101
byte = byte | (1 << 0x05) | (1 << 0x04) | (1 << 0x03) | (1 << 0x02) ;Another way of doing this is to use a "fence" of ones:
Write a Method (WAM) which returns a "mask" in which bits from i to j are SET
mask = 0b00111100 ; byte = byte | mask ;
Example if i=2 and j=5 the return value (nammed as mask) will be:
The function prototype is given below:
j i | | V V Bit number 76543210 |||||||| VVVVVVVV mask = 0b00111100 <---- Return Value
unsigned char getFence(unsigned char i, unsigned char j) { unsigned char mask; return mask; }
WR Home Topic Home | Chapter: 1 2 3 |
<Previous | Next> |