Quote:
|
Originally Posted by seanwitte
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)))
|
I think that you've got a slight problem here: I suspect that the expression where (bit) is needs to be replaced with (bit - 1)
Example: Try to access the 3rd bit of 20. 20 = 00010100
00010100 >> 3 == 00000010, but
00010100 >> 2 == 00000101, yielding the correct digit in the correct place.
However, without the ternary operation here, you are likely to return a number of non-binary answers: as you just saw, running GETBIT (20, 3) would yield 2 as you have it written, or five after the (bit-1) correction.
One other correction: The comments you used are C++ style, and not valid in C. watch out!
I believe that corrected macos follow:
Code:
/* get a bit from a variable*/
#define GETBIT(var, bit) (( var & (1 << (bit-1) ) ) ? 1 : 0 )
/* set a bit to 1 */
#define SETBIT(var, bit) (var |= (1 << (bit-1)))
/* set a bit to 0 */
#define CLRBIT(var, bit) (var &= (~(1 << (bit-1))))