Wednesday, 5 December 2012

Worth Read #5

Bit manipulation 
Embedded systems always require the user to manipulate bits in registers or variables. Given an integer variable a, write two code fragments. The first should set bit 3 of a. The second should clear bit 3 of a. In both cases, the remaining bits should be unmodified. 
These are the three basic responses to this question: 
• No idea. The interviewee cannot have done any embedded systems work 
• Use bit fields. Bit fields are right up there with trigraphs as the most brain-dead portion of C. Bit fields are inherently non-portable across compilers, and as such guarantee that your code is not reusable.
• Use #defines and bit masks. This is a highly portable method and is the one that should be used. My optimal solution to this problem would be:

#define BIT3 (0x1 << 3)
static int a;
void set_bit3(void) {
a |= BIT3;
}
void clear_bit3(void) {
a &= ~BIT3;
}
Some people prefer to define a mask together with manifest constants for the set and clear values. This is also acceptable. The element that I'm looking for is the use of manifest constants, together with the |= and &= ~ constructs

this is very simple info I've given, but this simple question itself is sufficient for judging whether u r an embedded guy or not anta... so, think of it...

Enjoy...

No comments:

Post a Comment