Cisco Systems Interview Question Software Engineer / Developers
0of 0 votesWrite a function which sets the bits in an integer when start bit position and end bit positions are passed as argument.
For eg, if I call function setbit(2,4) , it should return 14. (1110)
least significant bit on 1st position and so on..
Team: Switching Softwares
Country: United States
Interview Type: Phone Interview
What about the below code, please give feedback
int setbits(int start, int end) {
int no = 0;
int i;
for(i = start -1 ; i <= end - 1; i++) {
no |= (1 << i);
}
return no;
}

Set the range of bits from #L (least) to #H(highest)
1. Set the bit #(H-L+1)
2. Subtract 1 from the result
3. Shift the result by L bits to right
Just omitting the corner case checks to make the code clean.
- ashot madatyan on May 07, 2012 Edit | Flag Reply#include <stdio.h> int set_bits_range(int start, int end) { return ( (1 << (end - start + 1)) - 1 ) << start; } int main (int argc, char *argv[]) { int rv = 0; rv = set_bits_range(3, 5); printf("%d\n", rv); return 0; }