5 Embedded C programming interview questions — Part 1
Welcome to this series on embedded software and C programming related interview questions. This series can be helpful to crack interview for beginners and intermediate embedded software developers. All the questions in this series is going to be the one that were asked to me in all the interviews that I have given during 7 years of my industrial experience.
1. How can you set or clear nth bit in a variable?
This question was asked to me in at least 90% of the interviews I have given so far that is why this is the first question of this post as well.
Now there can be many ways to do this but I am going to share the optimal solution (If you know a better solution please feel free to leave in comments for all of us :D )for it.
int setBit(int* flag, int bitNum){
if(bitNum < 0 || bitNum > 7) {
return -1;
}
*flag |= 1 << bitNum;
return 0;
}
int clearBit(int* flag, int bitNum){
if(bitNum < 0 || bitNum > 7) {
return -1;
}
*flag &= ~(1 << bitNum);
return 0;
}
First things first, in above example we are taking care of extreme cases first, in the programming interview you should never forget to cover boundary cases. After that with the help of bit shifting I am setting…