Quote:
|
Originally Posted by Joe Johnson
Hey, can anyone give me an idea about the relatative effeciency of the underlying assembly language code for using the shifting macros vs. using the union/structures method?
I suppose that most times the code ends up more or less identical but I wonder on this particular CPU with this particular compiler, if there is a major advantage one way or the other.
Your comments welcome...
Joe J.
|
Well, lets throw a sample together and see what we get:
First, the union method:
Code:
typedef struct bits {
unsigned char b0:1;
unsigned char b1:1;
unsigned char b2:1;
unsigned char b3:1;
unsigned char b4:1;
unsigned char b5:1;
unsigned char b6:1;
unsigned char b7:1;
} BITS;
typedef union bit_char {
unsigned char byte;
BITS b;
} BIT_CHAR;
main ()
{
BIT_CHAR test1;
test1.byte = 5;
test1.b.b2 = 1;
}
And the corresponding assembly:
Code:
000802 cfd9 MOVFF 0xfd9,0xfe6
000806 cfe1 MOVFF 0xfe1,0xfd9
00080a 52e6 MOVF 0xe6,0x1,0x0
00080c 0e05 MOVLW 0x5
00080e 6edf MOVWF 0xdf,0x0
000810 84df BSF 0xdf,0x2,0x0
000812 52e5 MOVF 0xe5,0x1,0x0
000814 52e5 MOVF 0xe5,0x1,0x0
000816 cfe7 MOVFF 0xfe7,0xfd9
00081a 0012 RETURN 0x0
And the macro version (using bit-shifting)
Code:
//get a bit from a variable
#define GETBIT(var, bit)(((var) >> (bit)) & 1)
//set a bit to 1
#define SETBIT(var, bit)var |= (1 << (bit))
//set a bit to 0
#define CLRBIT(var, bit)var &= (~(1 << (bit)))
main ()
{
char test1;
test1 = 5;
SETBIT(test1,2);
}
ASM:
Code:
000802 cfd9 MOVFF 0xfd9,0xfe6
000806 cfe1 MOVFF 0xfe1,0xfd9
00080a 52e6 MOVF 0xe6,0x1,0x0
00080c 0e05 MOVLW 0x5
00080e 6edf MOVWF 0xdf,0x0
000810 84df BSF 0xdf,0x2,0x0
000812 52e5 MOVF 0xe5,0x1,0x0
000814 52e5 MOVF 0xe5,0x1,0x0
000816 cfe7 MOVFF 0xfe7,0xfd9
00081a 0012 RETURN 0x0
So it appears that the compiler optimizes both methods to the same ASM code. Therefore I'd say that which to use is a matter of personal preference.